Read the elements of a struct in another function

-1

I need to access struct data in my CalcN function, how should I proceed?

    int main(){

    int calcn();

    struct user1{

    string Nome;
    int Dnx;
    int Nxhu;

};

struct user1 x;

x.Dnx = 4;
x.Nxhu = 3;

int ResultadoEZ = calcn();

cout << "Resultado =  " << ResultadoEZ << endl;

}

    int calcn(){

        int Resultado;

        srand ( time (0) ) ;

        //Resultado = // x.Dnx + (rand() % 4); Dados da Struct 

        return Resultado;

    }
    
asked by anonymous 25.11.2014 / 23:28

1 answer

3

The AP changed the question and put another example but the basis of what is done here serves the same thing. You need to pass the object with this structure through the parameter of function .

Read how functions work in C ++ .

Then you need to put a parameter to the function to receive this data.

int CalcJnxU(User1 x) {
    int Resultado;
    srand(time(0));
    Resultado = x.hNX2 + (rand() % 4);
    return Resultado;
}

And then it will call the function passing the data as argument .

User1 x;
x.Nome = "nome1"; //talvez essa variável nome1 exista em outro contexto, aí poderia mantê-la
x.NxZ = 20;
x.hNX2 = 2;
x.kJXU = 2;
CalcJnxU(x);

Note that the x of the function has the same name but would not have to be. You could put whatever variable name you want in the parameter. Then you are passing the value that is in x in Main() to x of function CalcJnxU() which are independent variables, with different memory allocations. The data will be copied from one variable to another (you can avoid this copy in this case, but let's not complicate it).

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

Note how my code always gets a lot easier to read regardless of what it does.

Then you will have to learn more advanced things. In the way it is coded there may be small inefficiencies. Of course you do not need to and can not even worry about this while learning the basics. It will also be useful to learn typedef but leave it later.

    
25.11.2014 / 23:56