0
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?

Jordan
  • 37
  • 3
  • `pArray` is a pointer point to int, `int *p[4]`, `p` is a pointer array. – zzn Jun 22 '17 at 02:49
  • n contains the size of the pointer and not the array that the pointer points to. The reason why sizeof(array) works is given [here](https://stackoverflow.com/questions/671790/how-does-sizeofarray-work) – nahzor Jun 22 '17 at 02:56
  • [Don't cast the result of `malloc` in C](http://stackoverflow.com/q/605845/995714) – phuclv Jun 22 '17 at 02:57
  • 1
    Arrays are *not* pointers. Arrays *decay* into pointers. Read the C FAQ. http://c-faq.com/aryptr/index.html – jamesdlin Jun 22 '17 at 02:57
  • You're calculating the size of a pointer. When you use `malloc`, you are responsible for knowing how much memory you allocated. Assuming `sizeof(int)==4`, then you allocated a single block of memory 40 bytes in size like `array`. 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, `pArray` points to a single `int` (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. –  Jun 22 '17 at 03:05
  • arrays are __not__ just pointers in C. Period! – Ajay Brahmakshatriya Jun 22 '17 at 03:37

1 Answers1

0

It does work. The macro

sizeof(pArray)

is returning the size of the pointer, pArray (which 4 bytes on a 32-bit processor and 8 bytes on a 64-bit processor.. Your quote, "arrays are just pointers in C" is not precisely correct.

This might help: https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays