[英]What is the correct way to initialize an array of pointer to struct?
I am trying to implement trie data structure:- 我正在尝试实现特里数据结构:-
typedef struct tries{
char university[20];
struct tries *path[10];
} tries;
tries* head = (tries*)malloc(sizeof(tries));
head->path = { NULL } ;
whenever I try to initialize all the elements of path array to NULL I am getting this error:- 每当我尝试将路径数组的所有元素初始化为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
how can I initialize all path array's elements to NULL 如何将所有路径数组的元素初始化为NULL
I am using this NULL value in my Insert and Search functions. 我在我的插入和搜索功能中使用了这个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);
}
}
Just use calloc()
instead of malloc()
and you'll get all 0
s in the the char
-array and all NULL
s into the pointer-array. 只需使用
calloc()
而不是malloc()
,您将在char
-array中获得所有0
,在指针数组中获得所有NULL
。
Change 更改
tries * head = (tries*)malloc(sizeof(tries));
to be 成为
tries * head = (tries*)calloc(1, sizeof(tries));
Also please note that 另外请注意
void
-pointer in C void
指针 sizeof
is an operator not a function sizeof
是运算符而不是函数 so just do: 所以就做:
tries * head = calloc(1, sizeof (tries));
And if you want this code line to be more robust, surviving the change of the type head
points to make it 而且,如果您希望此代码行更健壮,请保留类型
head
的更改以使其适应
tries * head = calloc(1, sizeof *head);
As you are dealing with struct
s which in fact are assignable you could do the following: 在处理实际上是可分配的
struct
,您可以执行以下操作:
const tries init_try = {0};
...
tries * head = malloc(sizeof *head);
if (NULL == head)
exit(EXIT_FAILURE);
*head = init_try;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.