C++ Void函数结构体参数传递后成员值未更新及返回结构体失败问题咨询
Hey there! Let's break down why your przeciwnik1 struct's members stay at 0, and walk through the easy fixes.
The Root Problem
Right now, your przeciwniklos function takes the przeciwnik parameter by value. That means when you call przeciwniklos(przeciwnik1), the function creates a copy of your original struct. Any changes you make inside the function only affect this copy—not the original przeciwnik1 in your main function. That's why the original struct's values never update.
Solution 1: Pass the Struct by Reference
This is the simplest fix. By passing a reference to your struct, the function will modify the original variable directly instead of a copy. Just add an & to the parameter in the function definition:
#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; struct przeciwnik{ string nazwa; int HP; int DMGmax; }; void przeciwniklos(przeciwnik& przeciwnik1) { // Add & here for reference przeciwnik1.HP = rand() % 51 + 100; // Generates 100-150 // Note: rand()%1 always returns 0, so DMGmax will always be 25. // If you want a range (e.g., 25-34), use rand()%10 +25 instead przeciwnik1.DMGmax = rand() % 1 + 25; cout << "HP przeciwnika: " << przeciwnik1.HP << endl; } int main() { przeciwnik przeciwnik1; // Ekwipunek eq1; // Assuming this is another struct you've defined srand(time(NULL)); przeciwniklos(przeciwnik1); // Call stays the same // Now przeciwnik1's HP and DMGmax are updated! cout << "Original HP: " << przeciwnik1.HP << endl; cout << "Original DMGmax: " << przeciwnik1.DMGmax << endl; return 0; }
Solution 2: Pass the Struct by Pointer
If you prefer working with pointers, you can pass the address of the struct to the function. Use -> to access struct members through the pointer:
void przeciwniklos(przeciwnik* przeciwnik1) { przeciwnik1->HP = rand() % 51 + 100; przeciwnik1->DMGmax = rand() % 1 + 25; cout << "HP przeciwnika: " << przeciwnik1->HP << endl; } // In main: przeciwniklos(&przeciwnik1); // Pass the address with &
Solution 3: Return a Struct Instance
You mentioned trying to return a struct but having trouble—here's the correct way to do it. Define the function to return a przeciwnik type, create a temporary struct inside the function, populate it, and return it:
przeciwnik przeciwniklos() { przeciwnik temp; temp.HP = rand() % 51 + 100; temp.DMGmax = rand() % 1 + 25; cout << "HP przeciwnika: " << temp.HP << endl; return temp; } // In main: przeciwnik przeciwnik1 = przeciwniklos(); // Assign the returned struct to your variable
Quick Note on Your Random Value
Your line rand()%1 +25 will always set DMGmax to 25 because rand()%1 can only return 0. If you want a range of values (e.g., 25 to 34), change it to rand()%10 +25—the %10 gives a number between 0-9, adding 25 shifts it to 25-34.
内容的提问来源于stack exchange,提问作者NimVrod

