int main()
{
int *pArray;
int array[10];
pArray = (int*)malloc( sizeof *pArray * 10 );
int n = sizeof(pArray);
int m = sizeof(array);
printf("pArray size:\t%d\tarray size:\t%d\n", n, m);
return 0;
}
In the code above, the result of the sizeof() operation for the pointer array, whose size was allocated using malloc(), is a value of 4, or the size of a single element. The sizeof() function, however, returns the correct value of 40 for the normal array.
I always hear "arrays are just pointers in C." If arrays and pointers are functionally identical, why does sizeof() not work with the pointer array?
pArrayis a pointer point to int,int *p[4],pis a pointer array.mallocin Cmalloc, you are responsible for knowing how much memory you allocated. Assumingsizeof(int)==4, then you allocated a single block of memory 40 bytes in size likearray. The difference is the fact that the compiler won't know how much you allocated because you allocated the memory at runtime, not compile time. As far as the compiler is concerned,pArraypoints to a singleint(unless it's a null pointer, in which case it points to nothing); you're the only one who will know that you have allocated 40 bytes.