size of struct and corresponding variable

前端 未结 6 1141
慢半拍i
慢半拍i 2021-01-14 07:53

If i define a char variable

char a;

and a structure with a single char member

struct OneChar {
char a;
};
<
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 08:31

    The case you list will be packed as a 1-byte structure under all ABIs I am aware of.

    But if you need to portably handle more complicated cases, best practice is to always use sizeof(struct OneChar) when computing memory sizes, and taking the offset of the field address when you need to compute addresses via a trick like:

    (char*)&(((struct OneChar*)0)->a) - (char*)0
    

提交回复
热议问题