Difference in printing out pointer value vs array

The reason for your error is the fact that you make ptr point to the next value before printing your current value(the value you actually want to be printed). Let's consider the first step of your for loop, line by line, and keep in mind that in the beginning you made ptr point to the first element of the array(int * ptr = arr;):

  1. (*ptr) += 2; - this line is equivalent to (*ptr) = (*ptr) + 2; which means "increase by 2 the value located in the memory address pointed by ptr", so now the first element of the array is 3 (ptr is unchanged, it points to the first element of the array).
  2. ptr++; - this line increments ptr, or in other words ptr will now point to the next memory location, in your case the second element of the array. First element is 3, the value of the second element is unchanged.
  3. printf("%d", (*ptr)); - this line prints the value stored in the memory location pointed by ptr, but you made ptr point to the next location in the previous line, so ptr is pointing, as I said before, to the second element.

I hope you understand what happens in the next steps of your for loop.


int arr[5] = { 1, 2, 3, 4, 5 };
    int * ptr = arr;

    for (int i = 0; i < 5; i++) {
        (*ptr) += 2;
        ptr++;
        printf("%d", (*ptr));
    }

The reason is you are incrementing the pointer first and then printing its content.

Perhaps you need to print the contents first then increment it to point next element.

int arr[5] = { 1, 2, 3, 4, 5 };
    int * ptr = arr;

    for (int i = 0; i < 5; i++) {
        (*ptr) += 2;
        printf("%d", (*ptr));
        ptr++;
    }

Tags:

C