Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

c - Is there a standard pointer size declaration?

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 for that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...