Problems with vectors and structs

Asked

Viewed 249 times

0

I’m kind of new to C++ (because the code is basic) and I’m having a certain problem with an exercise that is necessary to store the data of 10 people (name, date of birth and height) using structs.

The structs are:

typedef struct 
{
    char nome[50];
    float altura;
} pserhumano;

typedef struct 
{
    float dia;
    float mes;
    float ano;
 } dnasc;

And the two functions are:

 void CriaData(dnasc *D[], int i)
 {
     D[i]->mes = 1 + (rand() % 12);
     D[i]->ano = 1950 + (rand() % 49);
     D[i]->dia = 1 + (rand() % 30);
 }

 void InserirNome(pserhumano *Z[])
 {
     dnasc a[10];
     for (int contador = 0; contador < 10; contador++) {
       cout << "Insira o seu nome." << endl;
       gets (Z[contador]->nome);
       cout << "Insira a sua idade." << endl;
       cin >> Z[contador]->altura;
       CriaData(&a, contador);
      } 
 }

When compiling, the output is this:

athos@ubuntu:~$ g++ exercicio1.cpp -w -o a
exercicio1.cpp: In function ‘void InserirNome(pserhumano**)’:
exercicio1.cpp:35:33: error: cannot convert ‘dnasc (*)[10]’ to ‘dnasc**’ for  argument ‘1’ to ‘void CriaData(dnasc**, int)’
        CriaData(&a, contador);
                             ^
exercicio1.cpp: In function ‘int main()’:
exercicio1.cpp:43:19: error: cannot convert ‘pserhumano (*)[10]’ to ‘pserhumano**’ for argument ‘1’ to ‘void InserirNome(pserhumano**)’
 InserirNome(&b);
               ^

Basically, I’m having trouble dealing with a struct vector and passing it to the function. What could be done?

2 answers

1


Below is a possible solution to your problem.

typedef struct
{
    char nome[50];
    float altura;
} pserhumano;

typedef struct
{
    float dia;
    float mes;
    float ano;
 } dnasc;

 void CriaData(dnasc *D)
 {
     D->mes = 1 + (rand() % 12);
     D->ano = 1950 + (rand() % 49);
     D->dia = 1 + (rand() % 30);
 }

 void InserirNome(pserhumano *Z[])
 {
     dnasc a[10];
     for (int contador = 0; contador < 10; contador++) {
       cout << "Insira o seu nome." << endl;
       gets (Z[contador]->nome);
       cout << "Insira a sua idade." << endl;
       cin >> Z[contador]->altura;
       CriaData(&a[contador]);
     }
}

0

A brief explanation of what was happening, improving @ricardokiki’s response.

The variable a is a vector and when passing &a as argument of the function you were passing a pointer pointer, as the function waits only a pointer.

So we have the mistake:

"cannot convert ‘dnasc (*)[10]’ to ‘dnasc**’..."

Browser other questions tagged

You are not signed in. Login or sign up in order to post.