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

Popular posts from this blog

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -

PHPMotion implementation - URL based videos (Hosted on separate location) -