【发布时间】:2017-12-02 09:52:38
【问题描述】:
我正在尝试实现 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);
}
}
【问题讨论】:
-
C 不允许分配给数组。
-
48在year[i]%48中的使用很奇怪。 -
年份 char 将包含一个类似于“1994”的值,因此在逐个访问位置时,我只剩下 char 值,它们具有从 48 开始的等效 ASCII 值,即 0 和 49 1、2 分别为 50 以此类推。现在通过使用 48 对其进行修改,我将获得 0-9 范围内的 pos 值,这些位置将保存指向我将创建的新节点的指针的值,在指向结构的指针的数组中。
标签: c pointers data-structures