</>EmbeddedInterview

What is the difference between an array and a pointer?

MediumC Programming

Short answer: An array is a block of contiguous objects; a pointer is a variable that holds an address. In most expressions an array name decays into a pointer to its first element, which is why they often look interchangeable. They differ in sizeof, in &, in assignment, and in how they are stored.

int arr[10];
int *ptr = arr;          /* arr decays to &arr[0] */

sizeof arr               /* 40: the whole array */
sizeof ptr               /* 4 on 32-bit, 8 on 64-bit: just the pointer */

&arr                     /* type int (*)[10]: pointer to the whole array */
&ptr                     /* type int **: address of the pointer variable */

arr = ptr;               /* error: an array is not assignable */
ptr = arr + 1;           /* fine */

arr[3] == *(arr + 3) == *(ptr + 3) == ptr[3] == 3[arr]   /* all the same element */

Where an array does not decay: as the operand of sizeof, of &, and as a string literal used to initialise a char array.

Function parameters: void f(int a[10]) is exactly the same as void f(int *a). The 10 is ignored, and sizeof a inside f gives the pointer size, a classic bug:

void clear(int a[10]) { memset(a, 0, sizeof a); }   /* clears only 4 or 8 bytes! */
void clear(int *a, size_t n) { memset(a, 0, n * sizeof *a); }   /* correct */

Storage difference:

char s1[] = "hello";     /* an array of 6 chars, writable copy */
char *s2  = "hello";     /* a pointer to a string literal, which must not be modified */

Multi-dimensional arrays: int m[3][4] decays to int (*)[4] (pointer to a row), not to int **. Passing it to a function expecting int ** is wrong; declare void f(int m[][4]) or void f(int (*m)[4]).

Count elements safely: #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) works only on real arrays, not on pointers; GCC/Clang can be made to reject pointers with a __builtin_types_compatible_p check (as the Linux kernel's version does).