Sizeof arrays and pointers

“…after all it’s just a pointer…”? No. Array is not a pointer. Array is an array object: a solid continuous block of memory that stores the array elements, no pointers of any kind involved. In your case array has 6 elements of size 4 each. That is why your sizeof evaluates to 24.

The common misconception about arrays being pointers has been debunked millions of times, but somehow it continues to pop up now and then. Read the FAQ, come back if you have any questions about it

http://c-faq.com/aryptr/index.html

P.S. As @Joachim Pileborg correctly noted in his answer, sizeof is not a function. It is an operator.


Another context in which arrays behave differently from pointers is the unary & operator (the “address of” operator). When unary & is applied to a pointer of type int * is produces a pointer of type int **. When unary & is applied to an array of type int [10] is produces a pointer of type int (*)[10]. These are two very different types.

int *p = 0;
int a[10] = { 0 };

int **p1 = &p;      /* OK */
int **p2 = &a;      /* ERROR */
int (*p3)[10] = &a; /* OK */

It is another popular source of questions (and errors): sometimes people expect & to produce a int ** pointer when applied to an int [10] array.

Leave a Comment