Is there a standard pointer size declaration?

不羁的心 提交于 2019-12-01 20:21:53

sizeof (void *)

Do you want the C-standard answer, or the answer that works pretty much all the time?

Usually, all pointers to data are the same size, which is sizeof(void*).

But since you tagged "C" and "standards", note that this is not required by the C standard. I think it is required by POSIX, and is also true on Win32, and none of the common modern architectures have instructions involving different-sized pointers. One scenario where you have different-sized pointers is segmented memory architectures with "near" and "far" pointers, although of course only one of those can be a "plain" pointer in C on any given implementation. Another scenario, is that in theory a pointer to int could be 2 bits smaller than a pointer to char, if an int is always 4-aligned. If the memory space was, say, 64MB, that could mean that an int* fits in 2 bytes, whereas a char* or void* requires 3. So the C standard allows different sizes for different types, in this case sizeof(int*) < sizeof(char*).

So, both for clarity, and a guarantee of correctness, if p is a pointer then its size is sizeof p.

As Steve Townsend says in his comment, it seems likely that if you ask another question about your code, you may be able to fix your real problem. Knowing the size of a pointer does not directly tell you much about the layout of a struct containing a pointer.

If you are looking for a portable way to find the offset in bytes of a structure member then you want to use the offsetof() macro defined in stddef.h:

#include <stdio.h>
#include <stddef.h>

int main(void)
{
    struct s {
        int i;
        char c;
        double d;
        char a[];
    };

    /* Output is compiler dependent */

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

    return 0;
}

Output

$ ./a.out
offsets: i=0; c=4; d=8 a=16
sizeof(struct s)=16

You can use sizeof(void*) directly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!