This is my makefile file all: trie
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
and header file
#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
and trie.c file
#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
}
it occurs error message in the main file
#include <stdio.h>
#include <stdlib.h>
#include "trie.h"
int main() {
node* x = (node*) malloc(sizeof(node));
insert("hi", x);
return 0;
}
and this is error message:
main.c: In function ‘main’: main.c:7:35: error: invalid application of ‘sizeof’ to incomplete type ‘node {aka struct node}’ node* x = (node*) malloc(sizeof(node));
have any idea why my code has an error?
Your main.c
doesn't have a definition of node
, just a declaration of the name without defining the structure. You either need to include the definition in the .h
file so both trie.c
and main.c
can see it, or you need to provide an allocator method (declared in trie.h
, defined in trie.c
) that can perform a definition aware allocation (and possibly initialization) of a node
in a place that has access to the definition of the otherwise opaque type.