Filling dynamic array of structs in C -
i allocate array of struct in function, cannot fill structures values in same function.
#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; }
in setsemaphores()
:
wait
pointer 1 variable of type struct sembuf
, not array of them.
thus, wait[3]
ub. wanted (*wait)[3].sem_op
.
another tip:
change *wait = malloc(n * sizeof(struct sembuf));
*wait = malloc(n * sizeof **wait);
.
that avoids using wrong type in sizeof.
Comments
Post a Comment