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?

6
  • pArray is a pointer point to int, int *p[4], p is a pointer array. Commented Jun 22, 2017 at 2: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 Commented Jun 22, 2017 at 2:56
  • Don't cast the result of malloc in C Commented Jun 22, 2017 at 2:57
  • 1
    Arrays are not pointers. Arrays decay into pointers. Read the C FAQ. c-faq.com/aryptr/index.html Commented Jun 22, 2017 at 2: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. Commented Jun 22, 2017 at 3:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.