我得到 4.0。
您所做的是将分配用于存储地址(x 和 y)的内存分别重新解释为 int 和 double。
您这样做了两次:当您将数据值分配给重新解释的内存时,以及当您打印它的副本时。这两种情况是不同的。
-
通过不兼容类型的指针写入内存是未定义的行为,并且已知像 gcc 这样的编译器在这种情况下会做一些有趣的事情(陷阱或忽略代码)。对此有曲折的讨论,包括 Linus Torvalds 的著名咆哮。它可能会也可能不会起作用。如果它有效,它可能会做预期的事情。 (对于正确的代码,您必须使用联合或执行 memcpy。)
它工作的一个条件是您的数据类型不需要比指针更多的空间。在 32 位架构上(可能是 64 位 Intel CPU 的 32 位编译器),双精度将比 4 字节地址长(IEEE 754 双精度有 8 字节)。 *y = 4.0; 写入超出y 的内存,覆盖堆栈上的其他数据。 (注意y 指向它自己,所以分配给*y 会覆盖y 自己的内存。)
-
将指针值作为参数传递给printf,转换规范分别为%d。 %lf 也未定义。 (实际上,如果转换规范为%p 并且指针值未强制转换为void *,则它已经未定义;但这通常被忽略且与常见架构无关。) printf 将仅解释堆栈上的内存(这是一个副本的参数)作为一个int resp。双重身份。
为了理解发生了什么,让我们看一下 main 堆栈上的内存布局。我写了一个详细说明它的程序;来源如下。在我的 64 位 Windows 上,可以正确打印 4.0 的双精度值;指针变量y 大到足以容纳double 的字节,并且所有8 个字节都被复制到printf 的堆栈中。但是如果指针大小只有 4 个字节,那么只有这 4 个字节会被复制到 printf 的堆栈中,它们都是 0,并且超出该堆栈的字节将包含来自早期操作的内存或任意值,例如 0 ;-),哪个 printf 将读取以尝试解码双精度。
这是在各个步骤中对 64 位架构上的堆栈的检查。我用两个标记变量declStart 和declEnd 将指针声明括起来,这样我就可以看到内存在哪里。我会假设该程序也可以在 32 位架构上进行微小的更改。试试看,告诉我们你看到了什么!
更新:它在 ideone 上运行,它似乎有 4 个字节的地址。双重版本不打印 0.0 而是一些任意值,这可能是因为 4 个地址字节后面的堆栈垃圾。参照。 https://ideone.com/TJAXli.
上面输出的程序在这里:
#include <stdio.h>
void dumpMem(void *start, int numBytes)
{
printf("memory at %p:", start);
char *p = start;
while((unsigned long)p%8){ p--; numBytes++;} // align to 8 byte boundary
for(int i=0; i<numBytes; i++)
{
if( i%8 == 0 ) printf("\nAddr %p:", p+i);
printf(" %02x", (unsigned int) (p[i] & 0xff));
}
putchar('\n');
}
int len; // static allocation, protect them from stack overwrites
char *from, *to;
int main(void)
{
unsigned int declStart = 0xaaaaaaaa; // marker
int *x = (int *) 0xbbbbbbbbbbbbbbbb;
double *y = (double *)0xcccccccccccccccc;
unsigned int declEnd = 0xdddddddd; // marker
printf("Addr. of x: %p,\n of y: %p\n", &x, &y);
// This is all UB because the pointers are not
// belonging to the same object. But it should
// work on standard architectures.
// All calls to dumpMem() therefore are UB, too.
// Thinking of it, I'd be hard-pressed to find
// any defined behavior in this program.
if( &declStart < &declEnd )
{
from = (char *)&declStart;
to = (char *)&declEnd + sizeof(declEnd);
}
else
{
from = (char *)&declEnd;
to = (char *)&declStart + sizeof(declStart);
}
len = to - from;
printf("len is %d\n", len);
printf("Memory after initializations:\n");
dumpMem(from, len);
x = (int *)&x;
printf("\nMemory after assigning own address %p to x/*x: \n", &x);
dumpMem(from, len);
*x = 3;
printf("\nMemory after assigning 3 to x/*x: \n");
dumpMem(from, len);
//print val of pointer
printf("x as long: %d\n", (unsigned long)x);
y = (double *)&y;
*y = 4.0;
printf("\nMemory after assigning 4.0 to y/*y: \n");
dumpMem(from, len);
printf("y as float: %f\n", y);
printf("y as double: %lf\n", y);
printf("y as unsigned int: 0x%x\n", y);
printf("y as unsigned long: 0x%lx\n", y);
return 0;
}