0

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;
}
4

2 回答 2

3

改变这个: printf("ptr + %d = %d\n",i, *ptr++); /*<--- B*/

对此: printf("ptr + %d = %d\n",i, *(++ptr)); /*<--- B*/

如果使用后缀版本的增量运算符,则增量之前的对象的值由表达式按值返回。前缀增量运算符(此答案中的第二组代码使用)将通过引用返回增量对象。

于 2013-04-21T23:51:20.247 回答
0

*ptr++ 将在 printf 之后递增。您应该使用 *(++p)。

于 2013-04-21T23:48:55.113 回答