101 101 - 3 months ago 11
C Question

Assign value to field in array of nested structs

I have a function

test
that accepts a pointer to a structure. How can I set the value of a field in a structure in the nested structure array? The structures are created and deleted elsewhere, I just want to set the value.

typedef struct {
int a;
} inner_struct_t;

typedef struct {
int b;
inner_struct_t innerStructsArr[];
} outer_struct_t;

void test(outer_struct_t *outerStruct);

void test(outer_struct_t *outerStruct) {
outerStruct->b = 123; // set a value in the outer struct
(outerStruct->innerStructsArr)[0].a = 456; // but this DOESN'T work
}

Answer

Here's a complete example that should work for you:

#include <stdio.h>
#include <malloc.h>

typedef struct {
    int a;
} inner_struct_t;

typedef struct {
    int b;
    inner_struct_t *innerStructsArr;
} outer_struct_t;

void test(outer_struct_t *outerStruct, int n) {
    outerStruct->b = 123;                       // set a value in the outer struct
    outerStruct->innerStructsArr = malloc(sizeof(inner_struct_t) * n); // Allocate space
    outerStruct->innerStructsArr[0].a = 456;    // Assign a value
}

int main (int argc, char *argv[]) {
  outer_struct_t s;
  test(&s, 1);
  printf("b=%d, inner[0]=%d\n", s.b, s.innerStructsArr[0].a);
  free(s.innerStructsArr);
  return 0;
}