1

我是c编程的新学生,做了一个小程序来看看动作中,指针中++的所有组合。所以我编码:(我通过virtualbox在Ubuntu中运行它)

 #include <stdio.h>

 main()
 {
    int num = 1;
    int  *p = &num;

    printf("\nnum position: %p num value: %d\n", p, num);

    *p += 1;
    printf("\n---- *p += 1; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    *p++;
    printf("\n---- *p++; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    (*p)++;
    printf("\n---- (*p)++; -----\n");
    printf("num position: %p num value: %d\n", p, num);

    ++(*p);
    printf("\n---- ++(*p); -----\n");
    printf("num position: %p num value: %d\n", p, num);

    ++*p;
    printf("\n---- ++*p; -----\n");
    printf("num position: %p num value: %d\n\n", p, num);

 }

输出:

num position: 0xbfce07b8 num value: 1

---- *p += 1; -----
num position: 0xbfce07b8 num value: 2

---- *p++; -----
num position: 0xbfce07bc num value: 2

---- (*p)++; -----
num position: 0xbfce07bd num value: 2

---- ++(*p); -----
num position: 0xbfce08bd num value: 2

---- ++*p; -----
num position: 0xbfce08bd num value: 2

我已经了解了 ++ 的不同用法。但是我的问题是关于地址的(我只写了 4 位数字)

首先地址是:07b8
在第一次增量之后地址是07bc(增加 4(HEX))
在第二次增加之后地址是07bd(增加 1 (hex))第 3 次
递增后地址为08bd (增加 100 (hex))

为什么地址的递增不稳定?

4

2 回答 2

1

Your program has undefined behavior: your code cannot write to *p after it has been advanced, because at that point the pointer points to memory not allocated to an int. Because of the way your variables are declared it appears that after the first increment the pointer is actually pointing to itself! Printing the address of the pointer &p should confirm that.

To fix this issue, change your program as follows:

int data[] = {0,0,0,0,0,0,0,0,0,0};
int *p = data;

Now you can increment your pointer up to ten times without the risk of writing to memory outside of the range allocated to your program.

Note: %p expects a void* pointer, so you should insert an explicit cast.

于 2013-10-25T11:05:49.983 回答
-1

发生这种情况是因为操作系统通常不会按顺序分配内存作为开始,您可以在此处阅读更多内容。

于 2013-10-25T11:13:07.373 回答