我在函数中分配结构数组,但无法在同一函数中用值填充这些结构。
#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;
}
最佳答案
在setSemaphores()
中:
wait
是指向一个类型为 struct sembuf
的变量的指针,而不是指向它们的数组。
因此,wait[3]
是 UB。你想要的是 (*wait)[3].sem_op
。
另一个提示:
更改 *wait = malloc(N * sizeof(struct sembuf));
到 *wait = malloc(N * sizeof **wait);
。
这很容易避免在 sizeof 中使用错误的类型。
关于c - 在 C 中填充动态结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895818/