1 /*my_stddef.h*/ 2 /* 3 * 宏NULL。不指向程序聲明或分配的任何數據對象的數據對象指針的值。0,0L,(void *)0(與函數指針不兼容)。 4 * 宏offsetof,肯定一個結構成員和這個結構的起始位置的偏移量(以字節爲單位),展開爲一個size_t類型的整值常量表達式,表驅動函數。 5 * ptrdiff_t:2個指針相減的結果的有符號整數類型。(2個指針不能相加,標準定義的)。不用,移植性很差。 6 * size_t:sizeof操做符的記過的無符號整數類型。很是有用。 7 * wchar_t:整值類型,它範圍內的值能夠表示最大擴展字符集中全部成員的不一樣編碼值。用不到。 8 */ 9 #ifndef MY_STDDEF_H_ 10 #define MY_STDDEF_H_ 11 12 #define MY_NULL (void *)0 13 typedef int my_ptrdiff_t; 14 typedef unsigned int my_size_t; 15 typedef unsigned short my_wchar_t; 16 #define offsetof(T, member) ((my_size_t)&((T*)0)->member) 17 #endif 18 /*把一個整數0強制轉換爲一個指針類型,而後對其結果執行指針算術,c標準未定義,但offsetof實現用了,因此編譯器須要支持此*/
1 /*my_t_stddef.c*/ 2 #include <assert.h> 3 #include <limits.h> 4 #include <stdio.h> 5 #include "my_stddef.h" 6 7 typedef struct{ 8 char f1; 9 struct{ 10 float flt; 11 }f2; 12 int f3; 13 }Str; 14 15 static char *pc = NULL; 16 static double *pd = NULL; 17 static my_size_t offs[] = {offsetof(Str, f1), offsetof(Str, f2), offsetof(Str, f3)}; 18 19 int main(void) 20 { 21 my_ptrdiff_t pd = &pc[INT_MAX] - &pc[0]; 22 my_wchar_t wc = L'Z'; 23 Str x = {1, 2, 3}; 24 char *ps = (char *)&x; 25 26 assert(sizeof(my_ptrdiff_t) == sizeof(my_size_t)); 27 assert(sizeof(my_size_t) == sizeof(sizeof(int))); 28 assert(pd == &pc[INT_MAX] - &pc[0]); 29 assert(wc == L'Z'); 30 assert(offs[0] < offs[1]); 31 assert(offs[1] < offs[2]); 32 assert(*(char *)(ps + offs[0]) == 1); 33 assert(*(float *)(ps + offs[1]) == 2); 34 assert(*(int *)(ps + offs[2]) == 3); 35 printf("sizeof(size_t) = %u\n", sizeof(my_size_t)); 36 printf("sizeof(wchar_t) = %u\n", sizeof(my_wchar_t)); 37 puts("succes testing stddef.h"); 38 return 0; 39 }