繁体   English   中英

指针意外指向一个值而不是地址

[英]Pointer unexpectedly pointing to a value and not an address

int changeValue(int *a) {
    *a = 4;
     printf("a points to: %d\n", a);
     return 0;

}
int main() {
    int* b = NULL;
    printf("b points to : %d \n",b);
    changeValue(&b);
    printf("b points to : %d\n", b);
}

我得到的 output 是b指向 0, a指向某个地址 - 一切都符合预期 - 但突然间我得到b指向 4。

为什么它不指向地址?

我还注意到,如果我尝试显示*b的实际值,我会遇到读取访问冲突

您无法获取 nullptr 的值,这将引发 nullptr 异常。

#include <stdio.h>
int changeValue(int* a) {
    *a = 4;
    printf("a points to: %p a's value is: %d\n", a, *a);
    return 0;
}
int main() {
    int a = 0;
    int* b = &a;
    printf("b points to : %p \n", b);
    changeValue(b);
    printf("b points to : %p\n", b);
    return 0;
}

它会在 gcc 上生成 4 个警告,所以我将对其进行分解。

  1. 在 changeValue function 中,打印一段时间,否则您会收到警告,提示您在给出 int 时需要 %d
  2. 主要是,b 的 printf 显示指向的地址而不是 b 的值。
  3. 将 function 设置为 changeValue(b) 因为 b 已经是一个指针。

现在,请注意 %d 和 b 仍然在此处生成警告,但这只是为了显示 output。

#include<stdio.h>
int changeValue(int *a) {
    *a = 4;
     printf("a points to: %d\n", *a);
     return 0;
}

int main() {
    int* b = NULL;
    int a = 999;
    printf("b points to : %d \n",b);
    b = &a;
    printf("b has address %d points to : %d \n",b, *b);
    changeValue(b);
    printf("b points to : %d\n", *b);
}

如果我运行上面的代码,以下是我得到的 output。

b points to : 0
b has address 799914380 points to : 999
a points to: 4
b points to : 4

现在我们可以看到带有 %d 的 printf 并且只有一个指针 b 打印它的地址,而 *b 打印它的值。 请注意,如果在 b 为 NULL 时尝试 *b,则会出现段错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM