MK27, in his first post, he asked where he made a mistake in his comments.
Now we have a slight problem here, because he seems to be editing his posts, so we have no reference to go back to. SO, I am going to post the original code he had up, PROPERLY FORMATTED so its easier to read.
Code:
#include <stdio.h>
int main() {
int *ptr;
int arrayInts[10] = {1,2,3,4,5,6,7,8,9,10};
ptr = arrayInts; //ptr points at cell [0]=1
printf("The pointer is pointing to the first ");
printf("array element, which is %d.\n", *ptr); //print 1
printf("Let's increment it.....\n");
ptr++; //ptr points at cell [1]=2
printf("Now it should point to the next element,");
printf(" which is %d.\n", *ptr); //print 2
printf("But suppose we point to the 3rd and 4th: %d %d.\n", //print cells [2] [3] 3 4
*(ptr+1),*(ptr+2)); //ptr stays the same
ptr+=2; //ptr points at cell [3]=4
printf("Now skip the next 4 to point to the 8th: %d.\n",
*(ptr+=4)); //ptr points to cell[8]=9
//and we print the new ptr
ptr--; //ptr points to cell[7]=8
printf("Did I miss out my lucky number %d?!\n", *(ptr++)); //ptr points to cell[8]=9
//and prints it
printf("Back to the 8th it is then..... %d.\n", *ptr); //ptr points to cell[8]=9
//and prints it
return 0;
}
There, now we can see where his original errors were, and from what I can tell, there were 2.
1)
Code:
ptr+=2; //ptr points at cell [3]=4
printf("Now skip the next 4 to point to the 8th: %d.\n",
*(ptr+=4)); //ptr points to cell[8]=9
//and we print the new ptr
He made simple math error here. After ptr += 2, he correctly points out that ptr points to cell 3. Then on the next line, after (ptr += 4), he says that ptr points to cell 8.
3 + 4 != 8
2)
Code:
printf("Did I miss out my lucky number %d?!\n", *(ptr++)); //ptr points to cell[8]=9
//and prints it
Here he says that ptr first gets incremented and points to cell 8, and then the value gets printed. Which, as we know from the semantics of the postincrement operator, is just not true.
Once again, that will behave as if you had typed:
Code:
printf("Did I miss out my lucky number %d?!\n", *ptr);
ptr++;
as two separate statements.
Now, the += operator does NOT behave like the postincrement operator. The += operator will return the new value of ptr after the addition occurs. So you were correct the first time, you just did the addition wrong.