1
struct s { int i; char * c; } *obj; obj = malloc(sizeof(struct s)); 

Say for example we have a struct as defined above (or any struct in general, i just wrote the above one for the sake of example).

Then, what is better when using the sizeof operator

sizeof(struct s) or sizeof(*obj) ?

I prefer the first one since it makes more sense to me (clearly tells us that we're allocating memory for an object of struct s)

Also, using the second one can introduce logical errors (like the usual 'forgetting to dereference the pointer')

Can the first one cause any problems? I haven't had problems with it yet but just wanted to know whether what i'm doing is proper or not.

If so, can you please provide an example of where it can fail?

2

3 Answers 3

7

Then, what is better when using the sizeof operator

sizeof(struct s) or sizeof(*obj) ?

It's a matter of preference.

I prefer sizeof(*obj). If I later change the type of obj (say, struct s2), sizeof(struct s) will be out of date.

Sign up to request clarification or add additional context in comments.

1 Comment

I prefer sizeof(*obj) because, when used with a variable (rather than a type), the parentheses are optional (as sizeof is an operator, not a function), and I think sizeof *obj looks rather nice.
3

Either may be used.

sizeof(*obj) should always be used, though, because if the type of obj ever changes, this will still work. With sizeof(struct s), you will have a latent bug.

1 Comment

Yes, I see the flaw in my method. Changing the struct name would at least spit out errors but changing the type would be disastrous if not taken care of. I think i'll stick to the objects from now on. Thank you.
-2

I prefer the sizeof(struct s) despite if the structures name changes the code is out of date. My philosophy is thaat if the structure changes it is best to revist the code that uses it just to be on the safe side.

1 Comment

-1: sizeof(*obj) should always be preferred. If the type of obj ever changes, you will have a silent bug with sizeof(struct s).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.