Structs in Arrays: newb question

Having trouble with something I thought would be simple, I'm getting an error every time an odd number is entered. No idea why. I also had an issue with struct variables causing a segmentation fault when more then 6 were present. I'm more interested in solutions that alter the current code the least. Thanks in advance for any assistance.


Main
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

#include <iostream>
#include "person.h"

using namespace std;

int main()
{
    int population = 0;
    cout<<"Enter Population Up to 10000: "<<endl;
    cout<<"Integer Required"<<endl;
    cin>>population;
    while(population >10000 || population < 0)
    {
        cout<<"Please choose an integer between 0 & 100000"<<endl;
        cin>>population;
    }
    Person persons[population];

    generatePop(persons,population);






    return 0;
}


person header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <iostream>

struct Person {
         int neighborhood;
         int age;
         int family;
         int social;
         int status;
         int work;

};

void generatePop(Person persons[],int population);



#endif // PERSON_H_INCLUDED

Person cpp file
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

#include "person.h"


void generatePop(Person persons[],int population)
{

  int counter = 1;
  while(population != 0)
  {
   persons[counter].neighborhood = 1;
   persons[counter].work= 0;
   persons[counter].age = 0;
   persons[counter].family = 0;
   persons[counter].social = 0;
   persons[counter].status = 0;

   population--;
   counter++;

  }


  }


Line 18 is not valid C++. The size of the array must be a compile time constant. Some compilers do allow this, but doing so does not comply with the standard.

person.cpp You're indexing from [1] to [population]. Indexes in C++ are from [0] to [size-1]. persons[counter] (where counter=population) is not a valid array reference.

edit: The normal idiom for initializing a fixed number of instances is the for loop;
1
2
  for(int i=0; i<population; i++)
  {... }

Decrementing population is poor style. If you wanted to use population for something else in your function, you've lost the value of it.
Last edited on
Thank you Anon,

I will apply these changes and hopefully iron this out. I appreciate the guidance on the population counter as well, your critique makes sense.
Hi Anon,

I implemented the recommended changes and now everything is working as I would expect. Thanks again, I'm sure to have more questions later, perhaps you'll be able to assist again. ^^ I kinda hit a roadblock in my class when we hit overloaded operators and linked lists.
Topic archived. No new replies allowed.