[英]Segmentation fault (core dumped) in my pointer code c++
我目前正在制作一個旨在使用指針和結構更新學生數據的程序,但我收到了一個分段錯誤(核心轉儲)錯誤。 這是我使用的代碼:
#include <iostream>
using namespace std;
struct Person
{
char name[64];
int age;
char gender[12];
};
int main()
{
int loop;
cout << "how many student to input: ";
cin >> loop;
struct Person *ptr[loop], d[loop];
for(int c = 1; c < loop; c++){
Person *ptr[c], d[c];
ptr[c] = &d[c];
}
for (int a = 1; a <= loop; a++){
cout << "Name: ";
cin >> (*ptr[a]).name;
cout << "Age: " ;
cin >> (*ptr[a]).age;
cout << "Gender: ";
cin >> (*ptr[a]).gender;
}
cout << "\nDisplaying Information." << endl;
for (int a = 1; a <= loop; a++){
cout << "Name: " << (*ptr[a]).name << endl;
cout <<"Age: " << (*ptr[a]).age << endl;
cout << "Gender: " << (*ptr[a]).gender<<endl;
}
system("pause");
return 0;
}
我更喜歡初始化指針的方式
Person *p = new Person()
與
*p = &d // assigning the address
還有你說的Person *ptr[c], d[c];
在第一個 for 循環中,您每次都重新初始化具有不同大小的數組。 您不必這樣做,因為您之前已經聲明過它們,並且最終 C++ 中的數組索引從 0 開始到 n-1,其中 n 是數組的長度。
在進行這些更改時,您的主要內容應如下所示,
int main()
{
int loop;
cout << "how many student to input: ";
cin >> loop;
struct Person *ptr[loop], d[loop];
for (int c = 0; c < loop; c++) {
ptr[c] = &d[c];
}
for (int a = 0; a < loop; a++) {
cout << "Name: ";
cin >> (*ptr[a]).name;
cout << "Age: ";
cin >> (*ptr[a]).age;
cout << "Gender: ";
cin >> (*ptr[a]).gender;
}
cout << "\nDisplaying Information." << endl;
for (int a = 0; a < loop; a++) {
cout << "Name: " << (*ptr[a]).name << endl;
cout << "Age: " << (*ptr[a]).age << endl;
cout << "Gender: " << (*ptr[a]).gender << endl;
}
system("pause");
return 0;
}
你為什么要做Person *ptr[c], d[c];
在第一個for
循環中? 循環內聲明的變量范圍僅限於該循環。 此外,這些變量將隱藏在循環外聲明的其他同名變量。
所以,在你的情況下,語句ptr[c] = &d[c];
循環內部分配給循環本地的ptr
,不能從循環外的任何地方訪問。
稍后當您嘗試使用cin >> (*ptr[a]).name;
寫入數據時cin >> (*ptr[a]).name;
, 你是UB因為ptr
變量從未被初始化。
只需注釋掉Person *ptr[c], d[c];
在for
循環中,事情應該可以正常工作。
只需從 for 循環中刪除以下行,代碼應該可以正常工作:
Person *ptr[c], d[c];
在 for 循環中聲明這些變量是創建新變量,其范圍僅限於 for 循環。 因此,當您執行以下語句時:
ptr[c] = &d[c];
在 for 循環內,它實際上是在初始化在循環內聲明的指針“ptr”,而不是在循環外聲明的指針。 因此,最終在 for 循環外聲明的指針“ptr”永遠不會被初始化,從而導致代碼崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.