0

I have the following structs:

typedef struct {
    char name[25];
} Piece;

typedef struct {
   int num;   //number of positions *piece will have
   Piece *piece;
} Category;

I'm creating a function that fills the structs with information from a text file. How can I iterate this dynamic structures?

On static variables, for example Category category[50]; I would declare an iterator (int i=0;) and move around the array doing category[i] = ....

What would be the equivalent with this dynamic structures?

This is a schema on how my function works:

void foo (Category *category) {

    int num_of_categories = 5;   //It won't be 5 always 

    category = (Category*)malloc(sizeof(Category)*num_of_category);

    while () {
        category->num = ...;

        category->piece = (Piece*)malloc(sizeof(Piece)*category->num);

        while () {
           category->piece->name = ...;

           //How to go to the next piece position?
        }
        //How to go to the next category position?
    }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
user157629
  • 624
  • 4
  • 17
  • 1
    You can do `category[i].num` and `category[i].piece->name` or `category[i].piece[j].name`. – Fiddling Bits May 15 '20 at 18:03
  • 1
    Is this an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? it seems to be over-complicating the simpler `typedef struct { int num; char name[25]; } Piece;` – Weather Vane May 15 '20 at 18:06
  • 1
    Your function receives an argument, then ignore the argument and assign new buffer there. Why? – MikeCAT May 15 '20 at 18:06
  • @MikeCAT because `Category` will be declared in the main function to use ir later on the program and I want to fill the information using that function passing the struct by parameter – user157629 May 15 '20 at 18:08
  • 1
    You must [pass a pointer to pointer to modify](https://stackoverflow.com/questions/36075244/how-can-i-malloc-a-struct-array-inside-a-function-code-works-otherwise) or allocate an array in the main function and pass it to the function then. – MikeCAT May 15 '20 at 18:10
  • Also see [c - Do I cast the result of malloc? - Stack Overflow](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – MikeCAT May 15 '20 at 18:11

0 Answers0