Here is an example code of what I'm trying to achieve
typedef struct
{
int x_pos, y_pos;
} A;
typedef struct
{
A **arrayAp;
} B;
int main(void) {
B B;
int n = 10;
A *array[n];
B.arrayAp = array;
for (int i = 0; i < 10; i++)
{
B.arrayAp[i] = malloc(sizeof(A));
B.arrayAp[i]->x_pos = i;
B.arrayAp[i]->y_pos = i + 1;
}
printf("%d",B.arrayAp[0]->x_pos);
}
It works as I want it to work. I can access elements of "array" using "arrayAp" pointer. But when I try to move some of this code to function for example:
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
and then assign value that it returns to "arrayAp"
B.arrayAp = makeAnArray();
Now I can't access first element of the array. Program just crash.
printf("%d",B.arrayAp[0]->x_pos);
But starting from second element everything works the same.
But the bigger problem I get when I try to move to function this code:
void initializeAnArray(B *B)
{
for (int i = 0; i < 10; i++)
{
B->arrayAp[i] = malloc(sizeof(A));
B->arrayAp[i]->x_pos = i;
B->arrayAp[i]->y_pos = i + 1;
}
}
Seems like it has no effect. When i'm trying to access array member through "arrayAp" pointer i'm getting some "random" values from memory.
typedef struct
{
int x_pos, y_pos;
} A;
typedef struct
{
A **arrayAp;
} B;
A * makeAnArray()
{
int n = 10;
A *array[n];
return &array;
}
void initializeAnArray(B *B)
{
for (int i = 0; i < 10; i++)
{
B->arrayAp[i] = malloc(sizeof(A));
B->arrayAp[i]->x_pos = i;
B->arrayAp[i]->y_pos = i + 1;
}
}
int main(void) {
B B;
B.arrayAp = makeAnArray();
initializeAnArray(&B);
printf("%d",B.arrayAp[1]->x_pos);
}
Sorry for my poor English.