C语言 如何在printf中查看结构的地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6409669/
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
how to see address of a structure in printf
提问by Registered User
I have a function which returns address as following
我有一个函数返回地址如下
struct node *create_node(int data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->next=NULL;
printf("create node temp->data=%d\n",temp->data);
return temp;
}
where struct node is
结构节点在哪里
struct node {
int data;
struct node *next;
};
How can I see in printf("") the address stored in temp?
如何在 printf("") 中看到存储在 temp 中的地址?
UPDATE
If I check the adressed in gdb the addresses are coming in hex number format i.e.
0x602010 where as same address in printf("%p",temp)is coming in a different number which is different from what I saw in gdb print command.
更新
如果我检查 gdb 中的地址,地址以十六进制数字格式出现,即 0x602010,其中相同的地址printf("%p",temp)出现在不同的数字中,这与我在 gdb 打印命令中看到的不同。
回答by jv42
Use the pointer address format specifier %p:
使用指针地址格式说明符%p:
printf("Address: %p\n", (void *)temp);
回答by Scott Biggs
EDIT:Don't do this! It prints the address of the pointer, not what you want!
编辑:不要这样做!它打印指针的地址,而不是你想要的!
I had all kinds of trouble getting this to work, but here's something that the compiler (I use the simple "cc" unix command line) didn't complain about and seemed to give appropriate results:
我在让它工作时遇到了各种各样的麻烦,但是编译器(我使用简单的“cc”unix命令行)没有抱怨并且似乎给出了适当的结果:
struct node temp;
// ... whatever ...
printf ("the address is %p", &temp);
[Rather than deleting, I left this as an example of what NOT to do. -smb]
[我没有删除,而是将其作为不该做什么的示例。-smb]
回答by satish
enter code here
#include<stdio.h>
struct anywhere
{
double a;
int b;
char c;
float d;
}g;
int main()
{
printf("%p\n%p\n%p\n%p\n",&g.a,&g.b,&g.c,&g.d);
return 0
}
now we can get output: address of g.a vice versa
现在我们可以得到输出:ga 的地址反之亦然
we can print the structure variable address like this way and also how padding happening in the structures we can see by printing the address of the each and every member.
我们可以像这样打印结构变量地址,以及通过打印每个成员的地址,我们可以看到结构中的填充是如何发生的。
thank you all any mistakes and suggestions please ping comment .
谢谢大家 任何错误和建议请 ping 评论。

