Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading