c - ‘sizeof’ 对不完整类型的无效应用

标签 c struct sizeof forward-declaration

这是我的makefile文件 全部:尝试

trie: trie.o main.o
    gcc trie.o main.o -o trie -std=c11 -g -Wall

trie.o: trie.c trie.h
    gcc -c trie.c -o trie.o -std=c11 -g -Wall

main.o: main.c trie.h
    gcc -c main.c -o main.o -std=c11 -g -Wall

clean:
    rm -f *.o trie

和头文件

#ifndef TRIE_H
#define TRIE_H

struct node;
typedef struct node node;

//insert a word in a leaf
void insert(char* word, node* leaf);

#endif //TRIE_H

和trie.c文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "trie.h"

struct node {
  char* data;
  node* child[127];
};

void insert (char* word, node* leaf) {
  node* curr = leaf;
  for (size_t i = 0; i < strlen(word); i++) {//start from beginning of char to end
    if (curr == NULL) {
      curr = (node*)malloc(sizeof(node)); // if it's null, creating new node
      curr->data = "";
    }
    curr = curr->child[(int) word[i]];
  }
  curr->data = word; // set last node stored the word
}

主文件出现错误信息

#include <stdio.h>
#include <stdlib.h>

#include "trie.h"

int main() {
  node* x = (node*) malloc(sizeof(node));
  insert("hi", x);
  return 0;
}

这是错误信息:

main.c:在函数“main”中: main.c:7:35: 错误:“sizeof”对不完整类型“node {aka struct node}”的无效应用 节点* x = (节点*) malloc(sizeof(节点));

知道为什么我的代码有错误吗?

最佳答案

你的 main.c没有 node 的定义, 只是名称的声明而没有定义结构。您要么需要在 .h 中包含定义文件所以两者trie.cmain.c可以看到它,或者您需要提供一个分配器方法(在 trie.h 中声明,在 trie.c 中定义),该方法可以执行 node 的定义感知分配(以及可能的初始化)在可以访问其他不透明类型的定义的地方。

关于c - ‘sizeof’ 对不完整类型的无效应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43904700/

相关文章:

c - 重新分配结构会导致堆损坏

c - 灵活的数组成员是否会增加结构的大小?

c - 为什么 bpf 代码无法访问 cpumap_enqueue_ctx 的前 8 个字节?

c - 按出生日期对患者结构进行排序

c - 如何检查 switch 语句表达式中的结构数据值

java - 从 Java VM 获取 native 字大小

c - 了解我的结构的大小

c - 在 Gtk 中出现错误。什么原因?

c - 如何在 C 中对齐这样的数字?

c - 使用 avcodec_decode_audio4() 解码 AAC 时出错