sizeof是一個單目運算符,它的運算對象是變量或數據類型,運算結果為一個整數。運算的一般形式如下:
sizeof(<類型或變量名>)?
它只針對數據類型,而不針對變量!
若運算對象為變量,則所求的結果是這個變量占用的內存空間字節數;若運算對象是數據類型,則所求結果是這種數據類型的變量占用的內存空間字節數。
sizeof是一個使用頻率很高的操作符,經常用來獲取變量或數據類型所占用的內存空間的大小,下面的程序顯示了sizeof的用法。
#include <stdio.h>
struct Student
{
??? ??? int number;
???? char name[8];
};
enum season{
???? spring,s ummer, fall, winter
};
?
int main()
{
?? ?int a = 10;
?? ?float b = 3.5;
??? struct Student s1 = {1, “zhangsan”};
??? enum season myseason;
???
?? ?printf ("the size of char is %d bytes\n",sizeof(char));
?? ?printf ("the size of short is %d bytes\n",sizeof(short));
? ??printf ("the size of int is %d bytes\n",sizeof(int));
?? ?printf ("the size of a is %d bytes\n",sizeof(a));
??? printf ("the size of long is %d bytes \n",sizeof(long));
?? ?printf ("the size of long long is %d bytes \n",sizeof(long long));
??? printf ("the size of float is %d bytes \n",sizeof(float));
?? ?printf ("the size of b is %d bytes \n",sizeof(b));
??? printf ("the size of double is %d bytes \n",sizeof(double));
?? ?printf ("the size of struct Student is %d bytes \n",sizeof(struct Student));
??? printf ("the size of enum season is %d bytes \n", sizeof (enum season));
??? printf ("the size of myseason is %d bytes \n", sizeof (myseason));
?
???? return 0;
}
程序執行結果如下:
linux@ubuntu:~/book/ch4$ cc test.c –o test -Wall
linux@ubuntu:~/book/ch4$./test
the size of char is 1 bytes
the size of short is 2 bytes
the size of int is 4 bytes
the size of a is 4 bytes
the size of long is 4 bytes
the size of long long is 8 bytes
the size of float is 4 bytes
the size of b is 4 bytes
the size of double is 8 bytes
the size of struct Student is 12 bytes
the size of enum season is 4 bytes
the size of myseason is 4 bytes
從該結果中,可以清楚地看到不同數據類型及變量所占的字節數,讀者應該熟悉這些結果。還可以看到,變量所占用的空間,由其數據類型決定,與變量的值沒有關系。