C语言 整数指针到整数的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4872923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion of integer pointer to integer
提问by Star123
Tried following code to check what happens when we convert integer pointer to a integer .
尝试以下代码来检查当我们将整数指针转换为整数时会发生什么。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
int a;
p = (int *)malloc(sizeof(int));
*p = 10;
a = (int)p;
printf("%d\n",*p);
printf("%d \n",a);
return 0;
}
The output is : 10
135680008
Can anyone explain, the concept related to this conversion? Any links provided related to this topic would also be helpful.
谁能解释一下与这种转换相关的概念?提供的与此主题相关的任何链接也将有所帮助。
回答by xtofl
Apparently you confuse the pointer with the content of the pointer.
显然,您将指针与指针的内容混淆了。
As an analogy to the real world, you could say that, with me pointing at a bird, you want to convert my index finger to a bird. But there is no relation between the type 'bird' and 'finger'.
作为现实世界的类比,您可以说,当我指向一只鸟时,您想将我的食指转换为一只鸟。但是类型“鸟”和“手指”之间没有关系。
Transferring that analogy to your program: you are converting the object pointing to your intto an intitself. Since a C pointer is implemented as 'the number of a memory cell', and since there are lotsof memory cells available, it's obvious that (int)pwill result in a very big number.
这个比喻转移到你的程序:你的目标指向转换到你int到int自身。由于 C 指针被实现为“存储单元的数量”,并且由于有很多可用的存储单元,因此很明显这(int)p将导致一个非常大的数字。
Casting is a nasty thing. It's a coincidence that pointers are quite analogous to integers. If they were implemented as "the nthaddress of the mthmemory bank", you wouldn't be asking this question because there wouldn't have been an obvious relation, and you wouldn't have been able to do this cast.
铸造是一件令人讨厌的事情。指针与整数非常相似,这是一个巧合。如果它们被实现为“第m个内存库的第n个地址”,您就不会问这个问题,因为不会有明显的关系,并且您将无法执行此转换。
回答by peoro
135680008is the address in decimal (it would be 0x8165008in hex) to which pis pointing: the address of the memory area allocated with malloc.
135680008是指向的十进制地址(它将是0x8165008十六进制)p:分配给的内存区域的地址malloc。
回答by Matt Whitworth
Here you're printing out the memory address of a, but you're printing it as a signed decimal integer. It doesn't make too much sense as a format, because some high memory addresses, the exact boundary depending on your word size and compiler, will be printed as negative.
在这里,您打印的是 的内存地址a,但您将其打印为带符号的十进制整数。它作为一种格式没有太大意义,因为一些高内存地址,根据您的字大小和编译器的确切边界,将被打印为负数。
The standard is to print it as an unsigned hexadecimal padded with zeroes to 8 or 16 characters (really, this is dependent on the exact word-size again). In printf, this would be %#08X, so the memory address 0x243 would be printed as 0x00000243.
标准是将它打印为一个无符号的十六进制填充零到 8 或 16 个字符(实际上,这再次取决于确切的字长)。在 中printf,这将是%#08X,因此内存地址 0x243 将打印为 0x00000243。

