What is the difference between the name of an array and another pointer that points to the first element?

advertisements

There is an array A, defined as int A[10], and there is another pointer containing the base address, defined as int *ptr = A.

I recently saw this post How to find the 'sizeof' (a pointer pointing to an array)?, and I can't figure out what the difference between A and ptr is. Aren't both of them just possessing the base address of the array?

We can use both A[i] and ptr[i] interchangeably now, for some integer i less than 10.

So why is there a difference in result obtained on using sizeof()?


The array is an array. An array is a contiguous sequence of items in memory. For an array of n items the size reported by sizeof is n times the size of each item.

The pointer is a pointer. A pointer value is (in practice) the memory address of something. The size of a pointer is essentially the size of a memory address.

In some context an expression that refers to an array, decays to a pointer to the first item of the array, and that, combined with support for e.g. indexing notation used with pointers, can make pointers seem similar to arrays. The decays does not happen when you e.g. pass an array by reference, or where you use it as argument to sizeof, but it does happen when you e.g. add an integer to an array, like "Hello"+2. That doesn't make sense for an array as such, so the array expression decays (to a pointer type that can serve as argument to the built-in +).

On top of that, in some contexts an array type is adjusted to pointer type. For example, a function with signature void foo(int a[42]); is adjusted to void foo(int* a);. This means the function can be called with any pointer to int, regardless of whether it points to an element in an array. Array decay means you can call the function passing it the name of an array, but the type of a in the function is int*.