![](/img/trans.png)
[英]Pointer pointing to garbage value after passing the address in a function
[英]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 个警告,所以我将对其进行分解。
现在,请注意 %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.