-2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
George
  • 7

1 Answers1

2

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335