SPMcGee SPMcGee - 4 months ago 10
C Question

accessing pointer array within pointer structs in C

I've looked long and hard on this site for the answer to this question, but still can't seem to achieve my goal. The code compiles and works fine without the assignment statement I'm trying to add. The fact that everything is a pointer in this code is confusing the heck out of me but I can't change that, its not my code. I basically just want to override all the values of

x_array
(only in the first index of
bs
)to be the values stored in
y_array
. Here is the program structure:

typedef struct
{
double *x_array;
} b_struct;
typedef struct
{
b_struct *bs;
} a_struct;

void fun_1(a_struct *as);
void allocate_b(b_struct *bs);
void allocate_a(a_struct *as);
int main(void)
{
a_struct *as
as = (a_struct *)malloc(sizeof(a_struct));
allocate_a (as);
fun_1 (as);
// everything internal to sa is deallocated in separate functions
free (as);
return (0);
}
void allocate_a(a_struct *as)
{
int i;

if ((as->bs =(b_struct *)malloc(5*sizeof(b_struct))) == NULL)
{
printf("Error: Not enough memory!\n");
exit(1);
}
for(i=0;i<5;i++) allocate_b (&(as->bs[i]));
return;
}
void allocate_b(b_struct *bs)
{
if ((bs->x_array =(double *)malloc(10*sizeof(double))) == NULL)
{
printf("Error: Not enough memory!\n");
exit(1);
}
return;
}

void fun_1(a_struct *as)
{
int i;
double y_array[10]; // the values i need are read into this array
// the following line is what will not compile
for (i=0; i<10; i++) as->bs[0]->x_array[i]=y_array[i];
return;
}


I have tried many permutations of adding
&
and
*()
but every time I get:

error: expression must have pointer type


The code is very long and complex and I tried to just parse out what was pertinent to my specific question. I tried to make it a complete program, but I'm sorry if I botched some syntax. Hopefully, this is enough to understand what needs to happen for the assignment statement to work. Could someone please explain how to access each layer of these nested pointer structs and pointer arrays?

Answer
for (i=0; i<10; i++) as->bs[0]->x_array[i]=y_array[i];

In your code bs[0] is not a pointer, it's a b_struct. Change that line to:

for (i=0; i<10; i++)
    as->bs[0].x_array[i]=y_array[i];
            ^^^