2013-10-19 143 views
1

我剛剛開始學習C++,這是我用結構完成的第一部分代碼,但是當我運行它時出現了分段錯誤。我正在用g ++在linux中編譯它。任何人都可以看到錯誤在哪裏,我明白是什麼導致了細分錯誤,但我看不到是什麼造成了錯誤。C++分段錯誤結構

所有幫助表示讚賞。

#include <iostream> 
using namespace std; 

struct people 
{ 
string forename; 
string lastname; 
int age; 
}; 

int main() 
{ 
int num_numbers; //ask the user how many numbers the sequence will contain 
cout << "Enter how people will be entered : \n"; 
cin >> num_numbers; // stores the user input 

people peoples[num_numbers]; 

for(int x = 0; x < num_numbers; x++) 
{ 
    cout<<"Enter forename "<< x <<":\n"; 
    cin >> peoples[x].forename; 
    cout<<"Enter surname "<< x <<":\n"; 
    cin >> peoples[x].lastname; 
    cout<<"Enter age "<< x <<":\n"; 
    cin >> peoples[x].age; 
} 

for(int i = 0; i<= num_numbers; i++) 
{ 
    cout << peoples[i].forename; 

    cout << peoples[i].lastname; 

    cout << peoples[i].age; 
} 

//delete[] peoples; 
} 

回答

2

首先,這樣的:

people peoples[num_numbers]; 

是非標準的擴展。其次,在這裏:

for(int i = 0; i<= num_numbers; i++) 
//    ^^^^^^^^^^^^^^^ 

你會出界,因爲數組大小num_numbers有索引從0num_numbers - 1

+0

啊當然!感謝您的幫助。 – user1816464