尝试初始化结构数组时出现段错误

Seg fault when trying to init an array of structs

我只是想在 c 中使用一个单独的函数来初始化一个结构数组,但是当我调用该函数时,它会导致程序因段错误而崩溃。

我想做的就是初始化值并使用大小为 n 的循环将 pos = 设置为 k+1,常数为 20 任何人都可以提供帮助,也许他们是我完全缺少的东西,谢谢。

代码:

  #include <stdio.h>
    #define n 20
    
    typedef struct history {
        char* value;
        int pos;
    } hist;

hist* history_struct[n];

void init_struct() {
    /* this function will create an array of structs of size 20*/
    for (int k = 0; k < n; k++) {
        history_struct[k]->value = (hist*) malloc(sizeof(hist*));
        history_struct[k]->pos = k+1;
        printf("indexes = %d ", history_struct[k]->pos);
    }
    
}

我相信您已经声明了一个指向结构的指针数组,简单清理代码将使您摆脱似乎拥有的空指针。如果 value 只是一个 char*,那么您还可以以一种奇怪的方式使用 malloc,然后只需使用 sizeof(char*) 即可,而无需强制转换

hist history_struct[n];

    void init_struct() {
        /* this function will create an array of structs of size 20*/
        for (int k = 0; k < n; k++) {
            history_struct[k].value = malloc(sizeof(char*));
            history_struct[k].pos = k+1;
            printf("indexes = %d ", history_struct[k].pos);
        }
        
    }

所以我们删除了指针,这意味着我们回到了点符号而不是“->”,因为我们不再使用指针希望这有助于解决您的问题任何进一步的问题都可以问我