I'm trying to create a pointer to a 6
element int
in a function to return it later, so for that purpose I'm using malloc
, but it seems to be acting not as I expected. Here's the code:
int j = 0;
for (;j < 5; j++) {
int * intBig = malloc(j * sizeof(int));
printf("sizeof intBig - %ld\n", sizeof(intBig));
}
Prints the same number 8
bytes as the sizeof(intBig)
at each iteration. Whereas I would expect a series of 4, 8, 12, 16
. What am I missing in this instance?
This is because you're printing the size of an int *
. Such a pointer always has the same size. sizeof
is a compiler construct. It cannot know things that only occur at runtime, such as dynamic memory allocation. Would it be something like
int intBig[100];
then you would get the size of the array back (in bytes), because the compiler knows how large it is. But the result of the sizeof
operator is always a compile-time constant¹, so there is no way what you have there could yield anything else.
Besides, you have a memory leak there because you're not free
-ing your memory again.
¹ Variable Length Arrays (VLA) are an exception, but they were not used here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With