【问题标题】:What is the correct way to initialize an array of pointer to struct?初始化指向结构的指针数组的正确方法是什么?
【发布时间】: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 不允许分配给数组。
  • 48year[i]%48 中的使用很奇怪。
  • 年份 char 将包含一个类似于“1994”的值,因此在逐个访问位置时,我只剩下 char 值,它们具有从 48 开始的等效 ASCII 值,即 0 和 49 1、2 分别为 50 以此类推。现在通过使用 48 对其进行修改,我将获得 0-9 范围内的 pos 值,这些位置将保存指向我将创建的新节点的指针的值,在指向结构的指针的数组中。

标签: c pointers data-structures


【解决方案1】:

只需使用calloc() 而不是malloc(),您将获得char 数组中的所有0s 和指针数组中的所有NULLs。

改变

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

成为

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

另外请注意

  • 无需在 C 中强制转换 void-pointer
  • sizeof 是运算符而不是函数

就这样吧:

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

如果你想让这行代码更健壮,在head类型的变化中幸存下来

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

当您处理实际上是可分配的structs 时,您可以执行以下操作:

const tries init_try = {0};

...

  tries * head = malloc(sizeof *head);
  if (NULL == head)
    exit(EXIT_FAILURE);
  *head = init_try;

【讨论】:

  • UV for *alloc(... sizeof *head); idiom.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多