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)
?
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 thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With