使用64位linux系統測試。地址通常是8個字節,須要用long。下面的思路也能夠用於其餘類型。linux
使用sizeof數組
#include <stdio.h> int main() { printf("%lu\n", sizeof(int)); return 0; }
注意不要用%d
做爲佔位符,不然會出現警告:測試
test.c: In function ‘main’: test.c:6:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d\n", sizeof(int));
輸出:code
$ gcc test.c $ ./a.out 4
利用數組orm
#include <stdio.h> int main() { int a[2]; long size; size = (long)&a[1] - (long)&a[0]; printf("&a[0]:%p\n", &a[0]); printf("&a[1]:%p\n", &a[1]); printf("offset: %ld\n", &a[1] - &a[0]); printf("size: %ld\n", size); }
輸出:io
$ gcc test.c $ ./a.out &a[0]:0x7ffda3f2f040 &a[1]:0x7ffda3f2f044 offset: 1 size: 4