将未初始化的结构传递给函数,为什么它不为空?

时间:2014-05-05 02:58:43

标签: c struct

在这一段时间里,我一直在摸不着头脑。我正在创建没有任何值的节点(甚至尝试初始化它和指针并将其设置为NULL),但是当我进入插入函数时,head_不会计算为NULL。我可以检查head _-> id = NULL但我不认为我应该这样做。关于我做错了什么的任何想法?我正在尝试建立和遍历一个链表,我肯定没有一个良好的开端!输出是:

head_ = 不是空的!?

#include <stdio.h>
#include <stdlib.h>
struct node{
        int id;
        struct node *next;
    };
int main(void){
    struct node head;
    int entered_id;
    insert(&head, 1);
}
void insert(struct node* head_, int new_id){  
    printf("\nhead_ = %s", head_);
    if(!head_){
        printf("\nnull");
    }
    else
        printf("\nnot null!?");
    fflush(stdout);
}

2 个答案:

答案 0 :(得分:0)

结构体不是指向null的指针,因为它已被分配。如果它被声明为:

struct node *head;

然后,它可能指向NULL,但未定义。

struct node *head = NULL;

将保证其指向NULL。即使在这种情况下,您也无法以这种方式将其分配到另一个函数中。如果您插入了

head = malloc(sizeof(struct node));

然后,当main返回时,head仍然是NULL,你会有内存泄漏。

定义它的方式,

struct node head; //allocates sizeof(struct node) bytes on the stack of main, which is destroyed after main exits.

有意义吗?

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
struct node{
        int id;
        struct node *next;
    };
int main(void){
    struct node * head = NULL; // create a pointer instead of declaring structure variable
    int entered_id;
    insert(head, 1);
}
void insert(struct node* head_, int new_id){  
   // printf("\nhead_ = %s", head_); can you print structure as string?
    if(!head_){
        printf("\nnull");
    }
    else
        printf("\nnot null!?");
    fflush(stdout);
}

如果使用struct node head,它将创建一个占用空间的对象,因此不是NULL。你想要的是一个指向一个最初指向任何东西的对象的指针,因此是null。