简体   繁体   中英

sizeof operator and structs

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM