错误指针值的来源是什么?

时间:2015-02-16 08:02:16

标签: c storage

编辑:我知道第二个例子是错误的,我知道如何使它正确,我想知道错误值来自何处以及什么时候没有指向哪里? a如何成为2686744

的价值

我不知道我应该选择什么样的答案,所以我给了你们所有人一个赞成。也许以后会选择一个。

当我创建一个指针并尝试以下面的错误方式抓住它时:

int b = 5;
int *a;
a = &b;

据我了解,获取指向变量a的值的正确方法是

printf("value of a is: %d\n", *a);
printf("storage location of a is: %p\n", *a);

然后输出

value of a is: 5
storage location of a is: 00000005

但是当我这样做错误时输出指向什么?

printf("value of a is: %d\n", a);
printf("storage location of a is: %p\n", a);

我得到了输出

value of a is: 2686744
storage location of a is: 0028FF18

这是从哪里来的?是否有一个自动创建的存储位置,以及来自它的价值?

我希望你理解我,我的英语不是很好。谢谢

4 个答案:

答案 0 :(得分:2)

您的格式说明符令人困惑。

%d中使用printf时,稍后传递的参数应为int。 当您使用%p时,传递给它的参数应该是地址。 这里:

printf("storage location of a is: %p\n", *a);

您指示%p但是向其传递整数(a指向的对象的值),这是错误的和未定义的行为。

同样在这里:

printf("value of a is: %d\n", a);
printf("storage location of a is: %p\n", a);

首先是错的。实际上第二个是正确的,但你应该这样使用它:

printf("storage location of a is: %p\n", (void*)a);

答案 1 :(得分:1)

* 解除引用指针a

a = 0x0028FF18     // This is the virtual memory address of the variable b

printf("value of a is: %d\n", a);    // This prints it in decimal
printf("storage location of a is: %p\n", a);  // This prints it in hex

我相信你想要的是:

printf("value of a is: %d\n", *a);
printf("storage location of a is: %p\n", a);
//                                       ^

答案 2 :(得分:1)

这是错误的:

printf("storage location of a is: %p\n", *a);

应该是:

printf("storage location of a is: %p\n", a);

a是内存地址,而*a是获取该地址所含值的间接地址。

再次在这里:

printf("value of a is: %d\n", a);

a是地址 - 因此其UB使用%d格式说明符。

答案 3 :(得分:0)

printf("storage location of a is: %p\n", *a);

这是错误的,因为您使用错误的格式说明符打印出int

printf("storage location of a is: %p\n", (void *)a);

要获取存储在此位置的值

printf("value of a is: %d\n", *a);

是打印输出值的地址或指针所持有的值的正确方法。

  

这是从哪里来的?是否有自动创建的存储空间   a的位置和来自它的价值来源?

没有任何东西来自任何地方。你有一个指针,指向一些有效的内存位置,你试图打印出地址以及存储在其中的值,它应该如上所示完成。

相关问题