初始化struct指针数组的正确方法是什么?

时间:2017-12-02 09:52:39

标签: c pointers data-structures

我正在尝试实现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);
    }

}

1 个答案:

答案 0 :(得分:2)

只需使用calloc()代替malloc(),您就可以获得0 - 数组中的所有char和所有NULL的指针-array。

更改

tries * head = (tries*)malloc(sizeof(tries));

tries * head = (tries*)calloc(1, sizeof(tries));

另请注意

  • 无需在C
  • 中投射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;