• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C Question: sizeof operator

AgentEL

Golden Member
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?
 
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.
 
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.
 
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.
 
Back
Top