Actually the following question prompted this question:

struct addrinfo hints; memset(&hints, 0, sizeof(hints)); //так всё работает //но если memset(&hints, 0, sizeof(addrinfo)); //то почему то возникают проблемы 

Now I don’t understand if a variable of type A can occupy more (less) in memory than the size of this type? Example:

 struct aaa { ... }; struct aaa var; sizeof(aaa)!=sizeof(var)//можеь ли такое быть? и с чем это связано 

And in what cases we have to calculate exactly the size of the MOST variable in memory, and not the size of the TYPE of a variable.

  • As far as I know, always equal. The problem in the question you are referring to is apparently something else. - avp
  • This is why @avp doesn’t happen as I understood the structure’s correct vanishing. I will look at this moment in the debager. And what is the difference after all sizeof (type) from sizeof (variable). - rubeno4ka
  • one
    Actually, if you have C (and not C ++), then you need to write sizeof(struct addrinfo) (otherwise it just doesn't compile). If you have C and sizeof(addrinfo) , it means that there is a variable with that name and that is its size you are looking at. Maybe because of this, and errors in the "zeroing". / In my opinion, there is no practical difference between sizeof(тип) and sizeof(переменная) . - avp
  • 2
    As for the actual question - “in which cases we should calculate exactly the size of the MOST variable in memory, and not the size of the TYPE variable” - in most cases it is not worth using sizeof(TYPE) , only to check that some variable ) has the required size (for example, when working with a variable of one type, as if it were a different type). - avp
  • @avp, it seems to be with arrays - Grundy

1 answer 1

Is a variable of type A can occupy in memory more (less) than the size of this type?

No, he can not.

in which cases we must calculate exactly the size of the MOST variable in memory, and not the size of the TYPE of a variable.

For example, in such:

 #define N 100 struct a { /* ... */ }; /* ... */ struct a aa[N]; size_t i; for( i = 0; i < sizeof(aa)/sizeof(aa[0]); i++ { /* ... */ } 
  • Would you say that here m. (sizeof(struct a) * N) != sizeof(aa) ? - avp
  • @avp, I do not want. But using a variable instead of a structure seems much more logical, natural and understandable. Therefore, it can be said that in this case one should do so. But you can not do it. If the escape skill from lyuley pumped. :-) - PinkTux
  • Well, I also wrote in a comment like this (up to inversion) - almost always you need to use sizeof(var_name) - avp