Possible Duplicate:
Pointer Arithmetic: ++*ptr or *ptr++?
I do not understand what the difference is? Here is an example of a code that implements *ptr++
#include <stdio.h>
int my_array[] = {1,23,17,4,-5,100};
int *ptr;
int main(void)
{
int i;
ptr = &my_array[0]; /* point our pointer to the first
element of the array */
printf("\n\n");
for (i = 0; i < 6; i++)
{
printf("my_array[%d] = %d ",i,my_array[i]);
printf("ptr + %d = %d\n",i, *ptr++);
}
return 0;
}
The output is
my_array[0] = 1 ptr + 0 = 1
my_array[1] = 23 ptr + 1 = 23
my_array[2] = 17 ptr + 2 = 17
my_array[3] = 4 ptr + 3 = 4
my_array[4] = -5 ptr + 4 = -5
my_array[5] = 100 ptr + 5 = 100
When you change the second printf statement to printf(“ptr + %d = %d\n”,i, *(++ptr));
this becomes the ouput:
my_array[0] = 1 ptr + 0 = 23
my_array[1] = 23 ptr + 1 = 17
my_array[2] = 17 ptr + 2 = 4
my_array[3] = 4 ptr + 3 = -5
my_array[4] = -5 ptr + 4 = 100
my_array[5] = 100 ptr + 5 = -1881141248
Someone please explain the difference in detail so I can understand.
One increments the pointer BEFORE fetching what it points to, the other increments AFTER fetching from the pointer.
In the second example, you have stepped past the end of your array the last iteration, and you are printing (probably) the pointer that is in the memory location immediately after your array (or some random garbage)