当后续位置存储的值被修改时,指针变量的值发生变化

问题描述 投票:0回答:1

这是我执行的C代码。


    int *a, *b,*c,d;
    a=&d;
    printf("1 a=%p &d=%p\n", a,&d);
    b=a+1;
    printf("2 a=%p &d=%p b=%p\n", a,&d,b);
    c=a+2;
    printf("3 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *b=34;
    printf("4 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    d=342;
    printf("5 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *c=21;
    printf("6 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *b=37;
    printf("7 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *c=29;
    printf("8 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);

我得到的输出是出乎意料的,因为我预计 'a' 的值与 &d 保持相同。但实际输出是:

1 a=0x7ffd0267145c &d=0x7ffd0267145c
2 a=0x7ffd0267145c &d=0x7ffd0267145c b=0x7ffd02671460
3 a=0x7ffd0267145c &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464
4 a=0x7ffd00000022 &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464
5 a=0x7ffd00000022 &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464
6 a=0x1500000022 &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464
7 a=0x1500000025 &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464
8 a=0x1d00000025 &d=0x7ffd0267145c b=0x7ffd02671460 c=0x7ffd02671464

我尝试通过不同的修改进行实验

int *a, *b,*c,d;
    a=&d;
    printf("1 a=%p &d=%p\n", a,&d);
    b=a+4;
    printf("2 a=%p &d=%p b=%p\n", a,&d,b);
    c=a+8;
    printf("3 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *b=34;
    printf("4 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    d=342;
    printf("5 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *c=21;
    printf("6 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *b=37;
    printf("7 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    *c=29;
    printf("8 a=%p &d=%p b=%p c=%p\n", a, &d,b,c);
    return 0;

这给出了输出:

1 a=0x7ffc674b76dc &d=0x7ffc674b76dc
2 a=0x7ffc674b76dc &d=0x7ffc674b76dc b=0x7ffc674b76ec
3 a=0x7ffc674b76dc &d=0x7ffc674b76dc b=0x7ffc674b76ec c=0x7ffc674b76fc
4 a=0x7ffc674b76dc &d=0x7ffc674b76dc b=0x22674b76ec c=0x7ffc674b76fc
5 a=0x7ffc674b76dc &d=0x7ffc674b76dc b=0x22674b76ec c=0x7ffc674b76fc
6 a=0x7ffc674b76dc &d=0x7ffc674b76dc b=0x22674b76ec c=0x7ffc674b76fc
分段错误(核心转储)

是什么导致了这种意外行为?

c pointers
1个回答
0
投票

如果指针不存储对象的地址,则不能取消引用该指针,否则会导致未定义的行为。

(也就是说,您不能取消引用“空”地址。)

在您的代码中,取消引用

b
c
会导致未定义的行为。

如果你想让你的代码工作,你可以声明一个数组:

#include <stdio.h>

int main() {
    int d[3] = {1, 2, 3};
    int *a = &d[0];
    int *b = a + 1;
    int *c = a + 2;
    *a = 4;
    *b = 5;
    *c = 6;
    printf("%d %d %d\n", d[0], d[1], d[2]);
    return 0;
}

输出

4 5 6

© www.soinside.com 2019 - 2024. All rights reserved.