【问题标题】:Seg fault when trying to init an array of structs尝试初始化结构数组时出现段错误
【发布时间】:2021-05-18 15:58:48
【问题描述】:

我只是尝试使用 c 中的单独函数初始化一个结构数组,但是当我调用该函数时,它会导致程序由于 seg 错误而崩溃。

我要做的就是初始化值并使用大小为 20 的 na 常数循环将 pos = 设置为 k+1 >

代码:

  #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);
    }
    
}

【问题讨论】:

  • 您没有结构数组。您声明了一个指向结构的指针数组。这个表达式 history_struct[k] 产生一个空指针。
  • 将其更改为hist history_struct[n];,或者您需要在取消引用之前为history_struct 中的每个hist* 分配malloc 内存。此外,history_struct[k]-&gt;value = (hist*) malloc(sizeof(hist*)); 很奇怪。没有必要强制转换malloc 的返回值,在这种情况下,您将它转换为错误的东西。 valuechar*,而不是 hist*。此外,sizeof(hist*) 将是 4 或 8,具体取决于您的架构,并且是一种用于导出字符串长度的奇怪方法。
  • @VladfromMoscow 我该如何解决这个问题然后我从行 hist* history_struct[n]; 中删除指针但这现在导致循环中的其他错误
  • 您的 malloc 为指向 hist 的指针分配了足够的内存,但您想为 hist 分配内存并存储指向该 hist 的指针,因此请编写 history_struct[k]-&gt;value = malloc(sizeof(hist));
  • @WernerHenze 为什么我不能仅仅使用 malloc(sizeof(*char)) 那还不够

标签: c struct segmentation-fault


【解决方案1】:

我相信你已经声明了一个指向结构的指针数组,简单的代码清理将把你从你似乎拥有的空指针中分类出来。如果 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);
        }
        
    }

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

【讨论】:

  • 这解决了我的问题,我现在明白了,非常感谢!
猜你喜欢
  • 2020-07-30
  • 2020-01-08
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多