簡體   English   中英

C ++分段錯誤結構

[英]C++ segmentation fault Structs

我才剛剛開始學習c ++,這是我對結構所做的第一段代碼,但是當我運行它時,我遇到了段錯誤。 我正在用g ++在Linux中編譯它。 誰能看到錯誤在哪里,我知道是什么導致分段錯誤,但我看不到是什么原因引起的。

所有幫助表示贊賞。

#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;
}

首先,這是:

people peoples[num_numbers];

是非標准擴展名。 其次,在這里:

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

您超出范圍,因為大小為num_numbers數組的索引從0num_numbers - 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM