In C, an array and a pointer are closely related but not the same thing. In most expressions the name of an array "decays" into a pointer to its first element, and a[i] is defined as *(a + i). But an array is a block of elements with a fixed size, while a pointer is a variable that holds an address. This guide explains the array and pointer relationship in C, where they behave the same, and the places where they differ.
When an array name appears in most expressions, the compiler converts it to a pointer to its first element. That is why you can assign an array to a pointer and pass it to a function that takes a pointer:
Because a[i] means *(a + i), subscripting works on both the array and the pointer in exactly the same way.
Decay does not happen in three places, and these are where the difference shows:
sizeof: sizeof a is the size of the whole array, while sizeof p is the size of a pointer.& operator: &a has type int (*)[3] (pointer to the whole array), while &p has type int **.char array.You also cannot assign to an array name: a = p; is a compile error, but p = a; is fine. A pointer can be moved with p++; an array name cannot.
A parameter written as an array is really a pointer. These three declarations are identical to the compiler:
Inside the function, sizeof a gives the pointer size, not the array size. So you must pass the length separately:
This is why almost all C library functions that take arrays also take a size.
Two common ways to create a string behave differently:
sizeof arr is 6 (five letters plus the terminator), while sizeof ptr is the pointer size. Prefer const char * for literals so the compiler stops accidental writes.
A pointer to an array keeps the size in its type. This matters for multidimensional arrays, where only the first dimension decays:
Here grid decays to int (*)[3], a pointer to an array of three int. The compiler needs the column count to compute where each row starts. You may also declare the parameter as int m[][3], which means the same thing. Since C99, variable length parameters such as int cols, int m[][cols] are also possible.
No. An array is a distinct object with its own size. It converts to a pointer in most expressions, but sizeof, & and initialisation treat it as an array.
The array parameter was adjusted to a pointer when you passed it, so sizeof returns the pointer size. Pass the element count as another argument.
Not directly. Return a pointer to heap memory, take a caller-supplied buffer, or wrap the array in a struct. Never return a pointer to a local array.
Yes, because both expand to *(a + i) and addition is commutative. It is only a curiosity and should not appear in real code.
An array name decays to a pointer to its first element, and a[i] is *(a + i), so the two are interchangeable in most code. They differ under sizeof, & and assignment, and array parameters are really pointers, so always pass the length alongside.