Reputation: 87
I have a question about pointers. I am beginning to grasp the concept, but this particular piece of code is threatening that understanding, and I just want to clear it up.
Please note line "B", which is printf("ptr + %d = %d\n",i, *ptr++); /*<--- B*/
I was under the impression that, since *ptr
was initialized to &my_array[0]
, then *ptr++
(which would translate to "whatever is at the address stored in ptr
, add one to it") would print out 23, which is the value at my_array[1]
.
Yet, it prints out the value at my_array[0]
, which is 1
.
I'm confused as to whether the ++
adds to the address itself (like, 1004 becomes 1005) and, since the integer takes up about 4 bytes of space, it would fall into the range of my_array[0]
(because that value, 1, would take up addresses 1001, 1002, 1003, 1004, and since my_array[0]
starts out at 1001 and only goes up to 1002, then *ptr++
would still print out my_array[0]
, which is 1
)...
or...
Whether *ptr++
goes from my_array[0]
(which is just *ptr
) to my_array[1]
*ptr++
, which is what I originally thought.
Basically, please explain what *ptr++
does to this program in particular. Please explain it to me as though I was a five year old.
I really appreciate it, and here's the code:
#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]); /*<-- A */
printf("ptr + %d = %d\n", i, *ptr++); /*<--- B*/
}
return 0;
}
Upvotes: 0
Views: 310
Reputation: 1265
Change this:
printf("ptr + %d = %d\n",i, *ptr++); /*<--- B*/
to this:
printf("ptr + %d = %d\n",i, *(++ptr)); /*<--- B*/
When you use the postfix version if the increment operator, the value of the object before the increment is returned by value by the expression. The prefix increment operator (which the second set of code in this answer uses) will return the incremented object by reference.
Upvotes: 3