Is there a standard pointer size declaration?

前端 未结 4 1361
无人及你
无人及你 2021-01-20 17:03

I have struct with padding in char (oops, my bad). I would like to subtract a pointer size. Do you know a standard pointer size declaration, or a standard macro

4条回答
  •  醉话见心
    2021-01-20 17:51

    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.

提交回复
热议问题