【问题标题】:Filling dynamic array of structs in C在 C 中填充结构的动态数组
【发布时间】:2014-04-06 15:11:09
【问题描述】:

我在函数中分配结构数组,但不能用同一函数中的值填充这些结构。

#include<sys/sem.h>

void setSemaphores(int N, struct sembuf **wait){

    *wait = malloc(N * sizeof(struct sembuf));

    wait[3]->sem_op = 99; //causes error: Segmentation fault (core dumped)

}

int main(int argc, char *argv[]) {

    int N = 4;
    struct sembuf *wait;

    setSemaphores(N, &wait);

    wait[3].sem_op = 99; //works fine

    return 0;
}

【问题讨论】:

  • 这无法编译(我发现的第一个错误是缺少N 的类型)。能否提供一个可编译的代码?
  • (*wait)[3].sem_op = 99;
  • 非常感谢,它有效

标签: c arrays dynamic struct


【解决方案1】:

setSemaphores():
wait 是一个指向struct sembuf 类型变量的指针,而不是指向它们的数组。
因此,wait[3] 是 UB。你想要的是(*wait)[3].sem_op

另一个提示:
更改*wait = malloc(N * sizeof(struct sembuf));
*wait = malloc(N * sizeof **wait);

这很容易避免在 sizeof 中使用错误的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 2018-09-07
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多