Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays in C a syntactic sugar for pointers?

Let's take a look at the following code:

int arr[n];
// s.t. i<n
arr[i] = 12;
// s.t. i<n 
*(arr + i) = 12;

Is arr[i] is a syntactic sugar for *(arr+ i) ?

like image 321
David Avatar asked Feb 18 '18 12:02

David


2 Answers

Yes you can say that- array subscript access is identical to pointer access with * dereference.

From 6.5.2.1p2 C11 standard N1570

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

This by no means should give you the impression that arrays are pointers. Interestingly when you apply [] the array decays into pointer to first element and that is being used to access the subsequent elements.

Array object is a different thing - there are cases when arrays don't decay into pointers. They are not syntactic sugar - you can consider one example -

int p[] = {1, 2 ,3};
int *t = p;
size_t sz1 = sizeof p;
size_t sz2 = sizeof t;
printf("%zu %zu\n", sz1, sz2);

Run this and I will understand something much more relevant to your question. An array can't be realized using something other than the array itself. Array access is identical to pointer dereference but that doesn't mean pointers take the position of array or vice versa.

Key takeaway or red pill of C programming:

Arrays are arrays and pointers are pointers. They are different thing.


By the way if sizeof tricked you a bit - don't worry there is a standard section saying that. From 6.3.2.1p3

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type 'array of type' is converted to an expression with type 'pointer to type' that points to the initial element of the array object and is not an lvalue...

Array doesn't get converted to pointer when used as an operand to sizeof. That's the thing. That's why you get what you get in earlier code snippet.

like image 134
user2736738 Avatar answered Sep 30 '22 03:09

user2736738


Yes, arr[i] is the same as *(arr+i) which is the same as *(i+arr) which again is the same as i[arr]

From Fabio Turati's comment: See "Why is a[5] == 5[a]" for more details.

like image 28
Gerhardh Avatar answered Sep 30 '22 01:09

Gerhardh