我正在尝试实现trie数据结构: -
typedef struct tries{
char university[20];
struct tries *path[10];
} tries;
tries* head = (tries*)malloc(sizeof(tries));
head->path = { NULL } ;
每当我尝试将路径数组的所有元素初始化为NULL时,我都会收到此错误: -
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow tries.c -lcrypt -lcs50 -lm -o tries
tries.c:20:18: error: expected expression
head->path = { NULL } ;
^
1 error generated.
make: *** [tries] Error 1
如何将所有路径数组的元素初始化为NULL
我在插入和搜索功能中使用此NULL值。
void Search(char* university, char* year, tries* head){
int pos = 0;
int length = strlen(year);
tries* temp = head;
for(int i = 0 ; i < length ; i++){
pos = (int) (year[i]%48);
if(temp->path[pos] != NULL){
temp = temp->path[pos];
} else {
printf("%s Not Found !!\n", university);
return;
}
}
if(strcmp(temp->university, university) == 0){
printf("%s is Presnt.\n", university);
} else {
printf("%s Not Found !\n", university);
}
}
答案 0 :(得分:2)
只需使用calloc()
代替malloc()
,您就可以获得0
- 数组中的所有char
和所有NULL
的指针-array。
更改
tries * head = (tries*)malloc(sizeof(tries));
是
tries * head = (tries*)calloc(1, sizeof(tries));
另请注意
void
- 指针
sizeof
是运营商而不是功能所以就这样做:
tries * head = calloc(1, sizeof (tries));
如果您希望此代码行更加健壮,那么在head
类型的更改中幸存下来以使其成为
tries * head = calloc(1, sizeof *head);
当您处理事实上可转让的struct
时,您可以执行以下操作:
const tries init_try = {0};
...
tries * head = malloc(sizeof *head);
if (NULL == head)
exit(EXIT_FAILURE);
*head = init_try;