Are arrays pointers?
New C/C++ programmers often have this confusion that all arrays are pointers. Well… they’re kinda, sorta, but not really. Let’s consider the following code:
1 2 3 4 |
char arr[5] = {'H','e','l','l','o'}; char *p = &arr[0]; printf("%c\n", p[2]); // l printf("%c\n", *arr); // H |
Try compiling the code snippets using Coding Ground.
The pointer p points to the first character of arr. Remember that the index operator ([]) is automatically converted to addition then dereference.
1 |
p[2]; // same as *(p + 2) |
Note: 2[p] would be evaluated to *(2 + p) giving us the same result as p[2]. It’s bad practice to use that form even if it works.
And dereferencing arr is similar to getting the first element
1 |
*arr; // same as *(arr + 0) which is arr[0] |
So when do arrays and pointers differ?