在C中填充结构的动态数组

时间:2014-04-06 15:11:09

标签: c arrays dynamic struct

我在函数中分配了struct数组,但是不能用相同函数的值填充那些结构。

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

1 个答案:

答案 0 :(得分:2)

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

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

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

相关问题