0

I have an array struct that is inside another struct, but I don't know how to print the value of the son struct in a function.

The main struct is something like:

 struct person{
    char name[10];
    int cash;
    listMov mov[];
};
typedef person Person;
Person user[50];

And the son struct

struct listaMovimenti{
    int bonifico;
    char beneficiario[10];
};
typedef struct listaMovimenti listMov;

listMov mov[2] = {{150, "Ponzi" },
                   {2000, "Gotti"}};

I've tried with something like this but with no success.

printf("Name %s and %d",user[0].mov[1].beneficiario, user[0].mov[1].bonifico); 
6
  • 1
    Define "no success". Did the code fail to compile? Did it crash? etc...etc... Commented Feb 19, 2018 at 16:59
  • And also include in your question the code that shows how you're populating user too Commented Feb 19, 2018 at 17:01
  • 3
    This is called flexible member array and it doesn't work that way. You must use dynamic allocation if you want to use that. Commented Feb 19, 2018 at 17:05
  • @ChrisTurner, beneficiario's string prints blank, the int bonifico prints 0. I populate user name and cash through a simply scanf. Commented Feb 19, 2018 at 17:07
  • But how do you populate user mov? It's different to the mov variable you've included code for Commented Feb 19, 2018 at 17:08

1 Answer 1

2

First:

The variable listMov mov[2] has no relation to the listMov mov[]; inside the struct. They have the same name but the scope is different. They are simply completely unrelated.

Second:

listMov mov[];

means you have a flexible array inside the struct. When you use a flexible array in a struct, you have to use dynamic memory allocation to reserve the amount of memory that you need. Using Person user[50]; is kind of meaningless as no memory is reserved for the flexible arrays.

Use of flexible arrays is a bit difficult. In most cases it is easier just to use a pointer like:

struct person{
    char name[10];
    int cash;
    listMov* mov;
};
typedef person Person;
Person user[50];

and then allocate memory like

user[0].mov = malloc(N * sizeof(listMov)); // N is thee number of elements needed

Then you can do:

user[0].mov[0].bonifico = 150;
strcpy(user[0].mov[0].beneficiario, "Ponzi");
user[0].mov[1].bonifico = 200;
strcpy(user[0].mov[1].beneficiario, "Gotti");

printf("Name %s and %d",user[0].mov[1].beneficiario, user[0].mov[1].bonifico);

Remember that you need a new malloc for every user[i] that you use.

Sign up to request clarification or add additional context in comments.

Comments

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.