【问题标题】:how to see address of a structure in printf如何在 printf 中查看结构的地址
【发布时间】:2011-09-18 13:48:40
【问题描述】:

我有一个函数返回地址如下

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;
}

结构节点在哪里

struct node {
        int data;
        struct node *next;
};

如何在 printf("") 中看到 temp 中存储的地址?

更新
如果我检查 gdb 中的地址,地址将以十六进制数字格式出现,即 0x602010 其中printf("%p",temp) 中的相同地址以不同的数字出现,这与我在 gdb print 命令中看到的不同。

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

    使用指针地址格式说明符%p

    printf("Address: %p\n", (void *)temp);
    

    【讨论】:

    • +1:对于过分热心(学究式正确)的编译器,将指针转换为void*:printf("%p", (void*)temp)
    • 为什么不直接打印东西的地址,比如printf("0x%08X", &temp);
    • @aroth:你不能保证 unsignedstruct node** 具有相同的表示形式:例如,你的 sn-p 在 64 位机器上非常失败
    • @pmg:我认为您的第一条评论重新转换为void * 仅适用于 C++ 吗?在 C 中,您可以将任何指针类型传递给需要 void * 的函数,不?
    • @Paul: printf 是一个接受可变数量参数的函数。第一个之后的参数没有“原型”。编译器不能强制该值是正确的类型,程序员必须手动执行。 我不懂 C++。
    【解决方案2】:

    编辑: 不要这样做!它打印指针的地址,而不是你想要的!

    我在让它工作时遇到了各种各样的麻烦,但编译器(我使用简单的“cc”unix 命令行)没有抱怨并且似乎给出了适当的结果:

    struct node temp;
    // ... whatever ...
    printf ("the address is %p", &temp);
    

    [我没有删除,而是将此作为不做的示例。 -smb]

    【讨论】:

    • 这是不正确的(请参阅其他答案进行讨论),此外,问题明确要求查看temp 而不是&temp
    • @M.M,是的,进一步的测试表明你是对的。这个答案打印的是指针的地址,而不是里面的值。
    【解决方案3】:
    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
    }        
    

    现在我们可以得到输出: g.a 的地址,反之亦然

    我们可以这样打印结构变量地址 以及通过打印每个成员的地址,我们可以看到结构中的填充是如何发生的。

    谢谢大家 任何错误和建议请平评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多