【问题标题】:Why the address of node is not assigned to the self referrential pointer of structure?为什么节点的地址没有分配给结构的自引用指针?
【发布时间】:2015-12-22 23:23:43
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

struct node
{
    int id;
    struct node *next;
};
typedef struct node NODE;
int main()
{
    NODE *hello;        
    hello=(NODE *) malloc(sizeof(NODE));
    hello->id=5;
    printf("\nAfter malloc\n");
    printf("address of hello: %d ",hello);
    printf("\n");
    printf("Value of Id is: %d , Value of next is: %u\n",hello->id,hello->next);
    return 0;
}

我尝试执行上面的代码,得到如下输出。

输出:

马洛克之后

你好地址:16949264

Id的值为:5,next的值为:0

我的问题是,为什么hello的值没有赋值给next?

【问题讨论】:

  • hellos-&gt;next 用于未初始化(未定义行为),并使用%p 打印变量的地址
  • 严格来说%p是用来打印void*的数据。尝试使用这个: printf("%p", (void*)hello->next);`
  • 为什么会这样? hello 不是 hello-&gt;next
  • @MikeCAT,你是对的,需要转换为 (void *)
  • 感谢您的回复,我有一个疑问,什么时候会在声明时或为它创建变量时为结构分配内存?

标签: c malloc dynamic-memory-allocation


【解决方案1】:

hello-&gt;next 不是hello,所以hellovalue 没有分配给hello-&gt;next

hello-&gt;next 也不是hello-&gt;value,所以hello-&gt;value 没有分配给hello-&gt;next

【讨论】:

    【解决方案2】:

    为什么hello的值没有赋值给next?

    为什么会这样?您已将内存分配给hello,因此它有一个next 还没有分配内存,所以它没有显示任何。 (说实话,是不确定的)。

    此外,要打印地址,您应该使用 %p 格式说明符和 printf(),并将相应的参数转换为 (void *)

    另外,Please see this discussion on why not to cast the return value of malloc() and family in C.

    【讨论】:

    • 感谢您的回复,我有一个疑问,什么时候会在声明时或为它创建变量时为结构分配内存?
    • @lok​​esh1729 指针变量的内存已分配,指针(它将指向)的内存需要分配。
    • @lok​​esh1729 尝试打印(void *)&amp;(hello-&gt;next) 并亲自查看。
    • 节点 *hi; printf("\n在 malloc 之前\n"); printf("\n节点地址为:%p",(void *)hi); printf("\n下一个地址是:%p",(void *)hi->next);
    • 在malloc节点的地址是:0x7ffda77a81b0之前得到这样的输出next的地址是:0x7ffda77aa470这里为什么节点和next的地址不同,next应该存储节点的地址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2023-03-25
    • 2020-07-02
    • 2023-04-06
    相关资源
    最近更新 更多