【发布时间】:2011-10-01 02:20:54
【问题描述】:
请在下面查看我的代码
#include <stdio.h>
#include <stddef.h>
typedef struct _node
{
int a;
char *s;
}Node, *nodePtr;
int main(int argc, char *argv[])
{
char *str = "string"; /*str points to satic storage area*/
Node nd;
nodePtr pNode = NULL;
size_t offset_of_s = offsetof(Node,s);
nd.a = 1;
nd.s = str;
pNode = &nd;
/*Get addr of s, cast it to a different data types pointer, then de-reference it*/
/*this works, print "string"*/
printf("%s\n", *(int*)((char*)pNode + offset_of_s));
/*this sucks, print (null)*/
printf("%s\n", *(float*)((char*)pNode + offset_of_s));
return 0;
}
我尝试获取Node结构的s成员的地址,cast它为不小于4字节的数据类型(4 strong> 字节是我机器上 pointer 的宽度),然后将指针取消引用作为 printf 的参数。
我确实认为两个 printfs 的结果应该是相同,但第二个显示 "(null)"。
float 和 int 在我的机器上具有相同的字节宽度,是导致这种情况的两种类型的内部不同表示吗?
提前致谢!
【问题讨论】:
标签: c pointers floating-point int printf