C: Pointer to an array of structs inside a struct within a function -




i pretty new c. created struct , array of structs store data , passed each of them functions:

int dosomething(struct s1 *struct1, struct s2 *struct2);  struct s1 {     int a;     int b;     int c; };  struct s2 {     double x;     double y;     double z; };   int main() {     int n = 200;     struct s1 s1;     struct s2 *s2 = malloc(n * sizeof(struct s2));      dosomething(&s1, &s2[0])      return 0; }  int dosomething(struct s1 *s1, struct s2 *s2) {     s1->a = 1;     s1->b = 2;     s1->c = 3;      s2[0].x = 1.1;     s2[1].x = 1.123233;     ...      return 1; } 

this got pretty annoying on time, decided put them together. doing this

struct s1 {     int a;     int b;     int c;     struct s2 *s2; };  struct s2 {     double x;     double y;     double z; };   int main() {     int n = 200;     struct s1 s1;     struct s2 *s2 = malloc(n * sizeof(struct s2));     s1.s2 = s2;      dosomething(&s1)      return 0; }   int dosomething(struct s1 *s1) {     s1->a = 1;     s1->b = 2;     s1->c = 3;      s1->s2[0].x = 1.1;     s1->s2[1].x = 1.123233;     ...      // or      struct s2 *s2 = s1->s2;     s2[0].x = 1.1;     s2[1].x = 1.123233;     ... } 

now, thing is: read lot pointers structs, arrays, arrays of structs , on, still not sure, if doing here correct. c: pointer array of pointers structures (allocation/deallocation issues), c pointer array of structs, how declare pointer array of structs in c, pointer array of struct in function. project growing size don't want make worse trying make better.

do need make array of pointers s2.s1[x]?

do need tell 1 pointer (struct s2 *s2 = s1->s2) how elements s2 has?

are there pitfalls or go wrong?

there nothing wrong it, matter of whether or not fits requirements , design choice in long term.

also, can do

s1.s2 = malloc(sizeof *s1.s2); if (s1.s2 == null)     error_handler(); // not use s1.s2 after dosomething(&s1); 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -

python - Read npy file directly from S3 StreamingBody -