掉入C語言的泥淖

offsetof

	#include <stddef.h>
	size_t offsetof(type, member);

The macro offsetof() returns the offset of the field member from the start of the structure type.

    struct s {
        int i;
        char c;
        double d;
        char a[];
    };

    /* Output is compiler dependent */

    printf("offsets: i=%zd; c=%zd; d=%zd a=%zd\n",
            offsetof(struct s, i), offsetof(struct s, c),
            offsetof(struct s, d), offsetof(struct s, a));
    printf("sizeof(struct s)=%zd\n", sizeof(struct s));

    exit(EXIT_SUCCESS);

size_t vs. uintptr_t

in C99, the standard introduced the intptr_t and uintptr_t types, which are signed and unsigned types guaranteed to be able to hold pointers.

size_t has to be big enough to contain the size of the largest possible object. uintptr_t must be big enough to contain any pointer. Given this, it is more or less guaranteed that sizeof(uintptr_t) >= sizeof(size_t) (since all of the bytes in the largest possible object must be addressable), but not more.

On machines with linear addressing, they probably will be the same size. On segmented architectures, on the other hand, it is usual for uintptr_t to be bigger than size_t, since an object must be in a single segment, but a pointer must be able to address all of the memory.


發佈了19 篇原創文章 · 獲贊 4 · 訪問量 5137
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章