I came across this in an assignment. Obviously * denotes a pointer but what does *(x+1) mean. I assumed it adds one to the address (x[0]) of x but this doesn't seem to be the case.
-
1For any array or pointer `a` and index `i`, the expression `a[i]` is *exactly* equal to `*(a + i)`. – Some programmer dude Oct 12 '22 at 08:17
-
*"it adds one to the address (x[0])"*. It adds the **size of one element**. – Weather Vane Oct 12 '22 at 08:18
-
@SouravGhosh no, you don't. One can very well start coding only knowing about `x[1]`. – Good Night Nerd Pride Oct 12 '22 at 08:27
-
Kind of a duplicate: [Do pointers support "array style indexing"?](https://stackoverflow.com/questions/55747822/do-pointers-support-array-style-indexing) – Lundin Oct 12 '22 at 08:34
1 Answers
It is the same as to write x[1]
. That is it yields the second element of the array.
From the C Standard (6.5.2.1 Array subscripting)
2 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).
Pay attention to that due to commutativity the expression *( x + 1 )
also may be written like 1[x]
.
The subscript operator is defined like
postfix-expression [ expression ]
So for example this expression
p++[i]
is equivalent to
*( p++ + i )
while this expression
++p[i]
is equivalent to
++*( p + i )
Here is a demonstration program
#include <stdio.h>
int main( void )
{
int x = 10;
int *p = &x;
printf( "x = %d, p = %p\n", x, ( void * )p );
printf( "p++[0] = %d, ", p++[0] );
printf( "p = %p\n", ( void * )p );
x = 10;
p = &x;
printf( "++p[0] = %d, ", ++p[0] );
printf( "p = %p\n", ( void * )p );
}
The program output is
x = 10, p = 00ACF930
p++[0] = 10, p = 00ACF934
++p[0] = 11, p = 00ACF930

- 301,070
- 26
- 186
- 335
-
Is there a reason why someone would prefer `*(x + 1)` over `x[1]`? – Good Night Nerd Pride Oct 12 '22 at 08:19
-
1@GoodNightNerdPride For example if you have a pointer p to a single object then the record *p is preferable than p[0] – Vlad from Moscow Oct 12 '22 at 08:21
-
1
-
1@VladfromMoscow `*p` doesn't contain any pointer arithmetic so it's not really the same thing. Rather, if you have a pointer to a single object then `*p` is preferable to `p[0]` _and_ to `*(p+0)`. – Lundin Oct 12 '22 at 08:37