Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in printing out pointer value vs array

Tags:

c

I have a question on printing out pointer value and array.

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

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

Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.

for (int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
}

I understand why the second one worked but still don't understand why first one didn't.

Expected output was 3 4 5 6 7 but the actual output of the first code was 2 3 4 5 -858993460

like image 405
jieun Avatar asked Jul 17 '19 09:07

jieun


2 Answers

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++;
    }
like image 184
kiran Biradar Avatar answered Oct 21 '22 07:10

kiran Biradar


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.

like image 33
Theodor Badea Avatar answered Oct 21 '22 08:10

Theodor Badea