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?
    }
6
  • 1
    You can do category[i].num and category[i].piece->name or category[i].piece[j].name. Commented May 15, 2020 at 18:03
  • 1
    Is this an XY problem? it seems to be over-complicating the simpler typedef struct { int num; char name[25]; } Piece; Commented May 15, 2020 at 18:06
  • 1
    Your function receives an argument, then ignore the argument and assign new buffer there. Why? Commented May 15, 2020 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 Commented May 15, 2020 at 18:08
  • 1
    You must pass a pointer to pointer to modify or allocate an array in the main function and pass it to the function then. Commented May 15, 2020 at 18:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.