使用指针将内存分配给结构

时间:2015-08-19 15:55:33

标签: c list struct

我有以下链接列表:

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

int main()
{
    struct node *l = 0;
    struct node *k = l;
    k = malloc(sizeof(struct node));
    /* l->d = 8; */
    return 0;
}

为什么注释代码使用错误?我不明白为什么没有为自k指向与l相同的节点指向的节点分配内存而我使用了{{1} } -pointer为它分配内存。

1 个答案:

答案 0 :(得分:5)

让我们分开吧。看看评论

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

int main(){
    struct node * l = 0;     // Now l = 0 (or NULL)
    struct node * k = l;     // Now k=l=0
    k = malloc(sizeof(struct node));   // Now k=<some address allocated>
    /*
    l->d = 8;                          // But l is still 0
    */
    return 0;
}

因此注释的代码试图取消引用NULL指针。

相关问题