Program won't return 0 as I told it too, program crashes.

Hi guys, I was told to create a program using compound data structure in order to store and display student details. It runs fine, until it reaches the end, then a windows error message appears "searching for a solution to my problem" and it returns a random huge number.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 #include <iostream>
#include <string>

using namespace std;

class details
{
   private:
   int num[10];
   string fnam[10];
   string snam[10];
   public:
   details();
}det1;

details::details()
{
    int i;
    int choice;
    cout<<"This program can only store 10 student's details."<<endl;
    for(i=1;i<11;i++){
    cout<<"Please enter student "<<i<<"'s student number: ";
    cin>>num[i];
    cout<<"Please enter student "<<i<<"'s forename: ";
    cin>>fnam[i];
    cout<<"Please enter student "<<i<<"'s surname: ";
    cin>>snam[i];
}
cout<<"Press 1 to view all student details"<<endl;
cout<<"Press 2 to Exit the program"<<endl;
cout<<"Enter your choice ";
cin>>choice;
if(choice==1)
{
    cout<<"1."<<fnam[1]<<" "<<snam[1]<<"("<<num[1]<<")"<<endl;
    cout<<"2."<<fnam[2]<<" "<<snam[2]<<"("<<num[2]<<")"<<endl;
    cout<<"3."<<fnam[3]<<" "<<snam[3]<<"("<<num[3]<<")"<<endl;
    cout<<"4."<<fnam[4]<<" "<<snam[4]<<"("<<num[4]<<")"<<endl;
    cout<<"5."<<fnam[5]<<" "<<snam[5]<<"("<<num[5]<<")"<<endl;
    cout<<"6."<<fnam[6]<<" "<<snam[6]<<"("<<num[6]<<")"<<endl;
    cout<<"7."<<fnam[7]<<" "<<snam[7]<<"("<<num[7]<<")"<<endl;
    cout<<"8."<<fnam[8]<<" "<<snam[8]<<"("<<num[8]<<")"<<endl;
    cout<<"9."<<fnam[9]<<" "<<snam[9]<<"("<<num[9]<<")"<<endl;
    cout<<"10."<<fnam[10]<<" "<<snam[10]<<"("<<num[10]<<")";
}
else if(choice==2)
{
cout<<"Exiting program";
}

}


int main()
{
    details();
    return 0;
}
Line 21: Given int num[10];, what are the valid values for i in num[i]?
Any integer :S
The problem is that there is no fnam[10].. If you recall declaring an array of 10 elements you put 10 like fname[10] //etc.. but all elements are only 0-9 .

in your for loop when variable i reaches 10 it would mean that you will save the file in the 10th element but the only element is available from 0-9 (10 elements) meaning if i is equal to 10 then you will save it in the 11th element which is none-existent. Thus you will have an error.

Out of scope or something like that.
Arrays start at 0, not 1. Hence, writing to fnam[10] or any other spot at 10 is invalid since you are writing to unallocated memory, which has unforseen consequences.
you aren't writing your class properly. Look up how to define constructors and destructors. Look up how to write functions too...

You can only call member functions of a class through an instantiation of the class.
Topic archived. No new replies allowed.