sizeof()函数用法与举例
1. sizeof(type)
sizeof(char)=1; sizeof(short)=2; sizeof(int)=4; // sizeof(int)=2 is C
sizeof(void *)=4;
Be careful about character variable and character constant in C:
ch = 'a'; sizeof(ch)=1; sizeof('a')=2; // 'a' is of type int
2. sizeof(variable)
e.g. int a; // sizeof(a)=4;
Be careful when dealing with the array or the pointer:
e.g.
char ch1[]="Hello"; // sizeof(ch1)=6; but strlen(ch1)=5;
char *ch2="World!"; // sizeof(ch2)=4;
When dealing with struct variables, the return value of sizeof() may be larger than you expected because of the bytes alignment.
e.g.
struct stru1 {int a; char c;} st1; //sizeof(struct stru1)=sizeof(st1)=8;
struct stru2 {int a; int b;} st2; //sizeof(struct stru2)=sizeof(st2)=8;
3. The macro offsetof() defined in <stddef.h>
We can use offsetof(struct stru1, b) to calculate the offset of domain c in struct stru1. Or we can use the following expression to access (assume struct stru1 *pst1)
*(int *)((char *)pst1 + offsetof(struct stru1, b)) = value;
Output:
sizeof(short) = 2, sizeof(a) = 2.
sizeof(short*) = 4, sizeof(*pa) = 4.
sizeof(char) = 1, sizeof(ch) = 1.
sizeof(char*) = 4, sizeof(pch) = 4.
sizeof(ch1) = 6, sizeof(*ch2) = 1, sizeof(ch2) = 4.
sizeof(struct stru1) = 8, sizeof(st1) = 8.
sizeof(struct stru2) = 8, sizeof(st2) = 8.
Press any key to continue . . .