C Question: sizeof operator

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
Here is the output:

sizeof test_ptr = 4
sizeof(test_ptr) = 4
sizeof test_ptr = 4
sizeof(test_ptr) = 4
sizeof test_ptr2 = 33
sizeof(test_ptr2) = 33

My question is: After test_ptr has been malloc'ed, why doesn't the sizeof report a size of 17? When I staticly allocated memory for test_ptr2, it has the output I expect.

From my understanding of C, when an array is initialized as char * array or char array[], it is the same thing. What am I missing?
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Because you're still checking the size of the pointer, not what it points to. You can use sizeof on arrays (on the stack), but you can't use it on dynamically allocated memory -- remember, sizeof is determined at compile time. And a pointer and array aren't the same thing.

And sizeof foo and sizeof(foo) are the same, so there's really no need to duplicate everything like that.
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
sizeof is providing the amount of memory that the variable requires to store infomration

Test_ptr is a 4 byte storage that will contain the address pointing to some data.
Test_ptr2 is 33 bytes of storage.

When you malloc you reserve memory and provide an address to where the memory is located.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Oh yeah, and test_ptr2 is *not* a pointer; it's an array. It only becomes a pointer when it decays to one, for example, when it's passed to a function that takes a pointer as an argument. If you point a pointer at your array, it'll be 4 bytes as well.