Struct array to function

How would you send an array of struct to a function to get all the structs populated?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

struct Enemy{
       int hp;
       int x;
       int y;
       }*enemy[199];

void populate(Enemy* enemy[199])
{
     for(int i=0; i==199; i++)
     {
             enemy[i].hp = rand()%400;
             enemy[i].x = rand()%1000;
             enemy[i].y = rand()%1000;
     }
}

int main()
{
    
    populate(enemy);
    
    for(int i=0; i==199; i++)
    {
            cout<<i<<endl;
            cout<<enemy[i].hp<<endl;
            cout<<enemy[i].x<<endl;
            cout<<enemy[i].y<<endl<<endl;
            }
            
    cin.get();
    
    return 0;
}


I have this but it claims that hp,x,and y are all undeclared in main. I've tried Enemy* enemy = new Enemy[199] and I have the same issue there too.
closed account (D80DSL3A)
A few problems I see. You are creating an array of 199 pointers to enemies, not 199 enemies.
Your for loop will not loop because i=0 to start and i==199 is false so loop is exited immediately.
Instead of explaining I will give the corrected code which works. Hope you will see why all the changes are made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
struct Enemy{
   int hp;
   int x;
   int y;
}enemy[199];// actual enemies, not just pointers to them

void populate(Enemy* p_enemy)// pass a pointer to the array of enemies
{
     for(int i=0; i<199; i++)// i<199 remains true for all desired iterations
     {
             p_enemy[i].hp = rand()%400;
             p_enemy[i].x = rand()%1000;
             p_enemy[i].y = rand()%1000;
     }
}


int main(void)
{		
	populate(enemy);    
    for(int i=0; i<199; i++)
    {
            cout<<i<<endl;
            cout<<enemy[i].hp<<endl;
            cout<<enemy[i].x<<endl;
            cout<<enemy[i].y<<endl<<endl;
    }


	cin.get();

	return 0;	
}


Actually, since you have declared the enemies array as global, it is visible to all functions. There is no need to pass anything to your populate(). You may hear from the anti-global-variable police here though.

1
2
3
4
5
6
7
8
9
void populate(void)
{
     for(int i=0; i<199; i++)
     {
             enemy[i].hp = rand()%400;
             enemy[i].x = rand()%1000;
             enemy[i].y = rand()%1000;
     }
}
Ahhh ok that makes sense. Thank you very much I've been stuck on that for a week now.

Yea it wasn't gonna stay global I just changed it to get it running.
Topic archived. No new replies allowed.