Problem with structures

I have a problem with this code. Program is intended to save some info about person, and then print it out at the end, but the console keeps on crashing.

What have I done wrong ?

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
37
38
39
40
41
#include <iostream>
#include <windows.h>

using namespace std;

struct peoples_info
{   string name;
    string lastname;
    int age;
};

int main()
{   int n;


    cout<<"Number of peoples...\n";
    cin>>n;

    peoples_info person [n];

    for(int i(0); i<n; i++){
        cout<<"\nName...\n";
        cin>>person[i].name;
        cout<<"\nLast name...\n";
        cin>>person[i].lastname;
        cout<<"\nAge...\n";
        cin>>person[i].age;
        system("CLS");
    }

    //it crashes here

   for (int i(1);i<=n; i++){
        cout<<"Name of the "<<i<<". person: "<<person[i].name<<endl;
        cout<<"Lastname of the "<<i<<". person: "<<person[i].lastname<<endl;
        cout<<"Age of the "<<i<<". person: "<<person[i].age<<endl;

    }

    return 0;
}


You are not making your loop right. To go through array ALWAYS start at i = 0 and end at i = n-1.
for(int i(0); i<n; i++) is ok (0 to n-1)
for (int i(1);i<=n; i++) is not (1 to n)

Also, you cannot do this in standard C++:
peoples_info person [n];
Standard complying compiler would reject that code, because size of array must be constant. The usual solution is to declare dynamic array with new keyword:
http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
thanks for a warning regarding for loop, I have fixed it.
And the code also works now when I've fixed the size of array to constant numb.

How could I then do that users input is used for the sice of an array ?
Last edited on
For a simple code as that, this would do:
1
2
3
peoples_info* person ; // declare it as pointer
cin >> n;
person = new peoples_info[n]; // set person to point to a new array in runtime 


The details are in the link in my last post.
You can also use a std::vector instead of an array:
http://www.cplusplus.com/reference/vector/vector/

Basically, you can probably just replace
peoples_info person [n];
with
vector<peoples_info> person(n); // initialize to n elements
and leave the rest of your code untouched (other than adding #include <vector> , of course), and it should work.
Great, thank you guys.
Will try both options first thing tomorow :)

Thanks for your help again :)
Topic archived. No new replies allowed.