0

So I have a void function that is going to randomly generte a structure:

This is the structure:

struct przeciwnik{
  string nazwa;
  int HP;
  int DMGmax;  
};

And the function:

void przeciwniklos(przeciwnik przeciwnik1)
{
  przeciwnik1.HP=rand()%51 + 100;
  przeciwnik1.DMGmax=rand()%1 + 25;
cout << "HP przeciwnika: " << przeciwnik1.HP <<endl;
}

And in the main function:

przeciwnik przeciwnik1;
 Ekwipunek eq1;

 srand(time(NULL));

  przeciwniklos(przeciwnik1);

However the HP and DMGmax stays 0. I tried using int przeciwniklos() but I couldn't return a structure,

NimVrod
  • 157
  • 1
  • 9
  • You need to read up on references. Right now you're modifying a local copy and then throwing that out. – tadman May 30 '21 at 11:33
  • Since you're using C++ you really should be working towards implementing this as functions *on the `struct` itself*. There's no reason to use this kind of procedural style when C++ gives you all the tools to write functions to initialize and/or modify an object as you wish. What you have here arguably should be in the constructor, minus the `cout` debugging code. – tadman May 30 '21 at 11:33
  • 1
    You are copying the structure in the function. To modify it in the function, you have to pass it as a reference. Change the function call to `void przeciwniklos(przeciwnik& przeciwnik1)`. The `&` indicates that it should be treated as a reference. – the_parzival May 30 '21 at 11:34

1 Answers1

0

in this code you are passing variable to function by value then function make copy of your function and do all works then since it's passed by value it has side effect you should return then assign to struct or make by reference.

return value:

przeciwnik przeciwniklos(przeciwnik przeciwnik1)
{
  przeciwnik1.HP=rand()%51 + 100;
  przeciwnik1.DMGmax=rand()%1 + 25;
  return przeciwnik1;
}
your_data_strucutre = przeciwniklos(your_data_strucutre);

pass by refrence:

void przeciwniklos(przeciwnik& przeciwnik1)
{
  przeciwnik1.HP=rand()%51 + 100;
  przeciwnik1.DMGmax=rand()%1 + 25;
  cout << "HP przeciwnika: " << przeciwnik1.HP <<endl;
}
przeciwniklos(your_data_strucutre);

pass pointer:

void przeciwniklos(przeciwnik* przeciwnik1)
{
  przeciwnik1->HP=rand()%51 + 100;
  przeciwnik1->DMGmax=rand()%1 + 25;
  cout << "HP przeciwnika: " << przeciwnik1->HP <<endl;
}
przeciwniklos(&your_data_strucutre);
N0ll_Boy
  • 500
  • 3
  • 6