0

Is *ptr++ same as *(ptr + 1)? I have an array named arr. Than > int *ptr = arr; The array conatins simple arithmetic integers such as: arr[0] = 0, arr [1] = 1..

printf(" Initial value of *ptr %d \n",*ptr);
*ptr++;
printf(" value of *ptr after *ptr++ %d \n",*ptr);
*(ptr++);
printf(" value of *ptr after *(ptr++) %d \n",*ptr);
*(ptr+1);
printf(" value of *ptr after *(ptr+1) %d \n",*ptr);
*ptr+1;
printf(" value of *ptr after *ptr+1 %d \n",*ptr);

The output is:

0
1
2
2
2

Is not the last value supposed to be 3 and 4 ? Is not *ptr++ = *ptr+1 or = *(ptr+1)?

Please help. Learning C concepts.

Arp
  • 43
  • 2
  • 8
  • 4
    Standalone `*(ptr+1);` is no-op. It does nothing. But `*ptr++;` changes the value of ptr. – keltar Nov 08 '14 at 15:11

1 Answers1

1

*(ptr++), *ptr++ both result in incrementing the value of pointer but not the +1 expression.

Let us say &a[0] i.e address of start of the array = 0x1000 (for simplicity). Let us assume size of each element in array as 4 bytes.

    x = *ptr++;    //x holds 0x1004 : ptr holds 0x1004
    x = *(ptr++);  //x holds 0x1008 : ptr holds 0x1008
    x = *(ptr+1);  //x holds 0x100C : ptr still holds 0x1008 (We have not modified ptr)
    x = *ptr+1;    //x holds 0x100C : ptr still holds 0x1008 (We have not modified ptr)

Hope that helps

jaikish
  • 11
  • 1