I am pretty new to C. I created a struct and an array of structs to store data and passed each of them to my 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 over time, so I decided to put them together. Now I am 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, the thing is: I read a lot about pointers to structs, to arrays, to arrays of structs and so on, but I am still not sure, if what I am doing here is correct. C: pointer to array of pointers to structures (allocation/deallocation issues), c pointer to array of structs, How to declare pointer to array of structs in C, Pointer to array of struct in function. My project is growing to a size where I just don't want to make it worse by trying to make it better.
Do I need to make an array of pointers to the s2.s1[x]?
Do I need to tell the one pointer (struct S2 *s2 = s1->s2) how much elements s2 has?
Are there any pitfalls or could something go wrong?