PDA

View Full Version : sizeof(pointer) in C?



crazyfuturamanoob
November 21st, 2008, 07:05 PM
Why does sizeof(pointer) give me always 4, no matter what is the pointer argument?

Does it give the size of the address itself? How to get the size of the pointer's content then?

I don't understand pointers too well. I have a good book, a lot e-tutorials, but I just don't get them.

psusi
November 21st, 2008, 07:15 PM
Why does sizeof(pointer) give me always 4, no matter what is the pointer argument?

Does it give the size of the address itself? How to get the size of the pointer's content then?


Yes, it gives you the size of the pointer, not what it points to. Dereference the pointer ( *foo ) and take the sizeof that if that is what you want.

bukwirm
November 21st, 2008, 07:19 PM
#include <stdio.h>

int main()
{
char c;
char* cp = &c;

printf("sizeof(char*): %d\nsizeof(char): %d\nsizeof(&char*): %d\n", sizeof(cp), sizeof(c), sizeof(*cp));
}

Does that answer your question?

(Except psusi beat me to it)

gpsmikey
November 21st, 2008, 08:43 PM
That is the number of bytes used to hold the pointer value. The only time that will typically change is on a different architecture - for example, the pointer size on an 8 bit machine will probably be 2 bytes (although not always).

mikey

CptPicard
November 21st, 2008, 09:05 PM
Then there is the added complication of arrays... I have even seen questions here where people assume that sizeof returns the length of the array that the dereferenced pointer is the first item of...

mike_g
November 21st, 2008, 09:22 PM
Then there is the added complication of arrays... I have even seen questions here where people assume that sizeof returns the length of the array that the dereferenced pointer is the first item of...
Thats understandable tho, especially if they are coming from a php background.