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

标签 c struct

我对这个问题已经挠头好一阵子了。我正在创建没有任何值的节点(甚至尝试初始化它和指针并将其设置为 NULL),但是当我进入插入函数 head_ 时,其计算结果不会为 NULL。我可以检查 head_->id = NULL 但我认为我不必这样做。关于我做错了什么有什么想法吗?我正在尝试构建并遍历一个链接列表,但肯定没有一个好的开始!输出为:

头_ = 不为空!?

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

最佳答案

#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节点头,它将创建一个占用空间的对象,因此不为NULL。您想要的是一个指向对象的指针,该对象最初指向任何内容,因此为空。

关于c - 将未初始化的结构传递给函数,为什么它不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464098/

相关文章:

c - 整数的“字符数组”到 'Integer array'

c - C 如何以 double 数据类型存储 1001 位数?

c - union 中的并行数组与严格别名有何关系?

在 C 中调用结构体

c# - 编码(marshal)结构数组和 IntPtr

c - Malloc 和 Realloc 不起作用(C11 - CLion)

c - libusb-1.0 libusb_get_device_list() 失败

c++ - 打印模板函数中的任何结构

c - C中结构中的段错误

C内存共享问题