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
179 views
in Technique[技术] by (71.8m points)

c++ - What is the size of a pointer?

Is the size of a pointer the same as the size as the type its pointing to, or do pointers always have a fixed size? For example...

int x = 10;
int * xPtr = &x;
char y = 'a';
char * yPtr = &y;

std::cout << sizeof(x) << "
";
std::cout << sizeof(xPtr) << "
";
std::cout << sizeof(y) << "
";
std::cout << sizeof(yPtr) << "
";

What would the output of this be? Would sizeof(xPtr) return 4 and sizeof(yPtr) return 1, or would the 2 pointers actually return the same size? The reason I ask this is because the pointers are storing a memory address and not the values of their respective stored addresses.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

Function Pointers can have very different sizes, from 4 to 20 Bytes on an X86 machine, depending on the compiler. So the answer is NO - sizes can vary.

Another example: take an 8051 program, it has three memory ranges and thus has three different pointer sizes, from 8 bit, 16bit, 24bit, depending on where the target is located, even though the target's size is always the same (e.g. char).


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

...