Search code examples
arrayscpointers

Why does incrementing a pointer to an array give this result?


If I define a new (int) array, and increment the dereferenced pointer to this array by 1, why do I get the following result?

int main()
{
    
    int myArray[1024];

    myArray[0] = 123;
    myArray[1] = 456;

    printf("%d \n", *myArray);
    printf("%d \n", *myArray+1);

    return 0;
}

The output is:

123 
124

Why is the next value not 456? And, why does the output skip over 3?


Solution

  • Operator precedence. The * binds more tightly, so the + 1 applies to the result of dereferencing. *(myArray + 1) would give you the result you expect, 456. As would the rather more idiomatic myArray[1].