我是C++新手(從我的代碼中可以看出),我正在使用指針和數組以及我的結構練習動態內存分配。我的代碼工作正常,直到它訪問「growArray」函數,然後它給我SIGSEGV錯誤。我不明白爲什麼,因爲據我可以告訴我正確地傳遞一個指針指針,並且我也爲新的指針分配空間。是我的結構的問題,還是傳遞指針的問題,還是接收指針的問題?我希望這個問題是有道理的。SIGSEGV,Segmentation fault
#include <iostream>
#include <string>
using namespace std;
struct FriendInfo
{
string name;
string address;
string number;
};
FriendInfo *growArray(FriendInfo *p_entry, int *size);
int main()
{
int curNum = 0;
int size = 2;
int userAnswer;
FriendInfo *p_friends = new FriendInfo[size];
cout << "Enter a friend's info?(1 for yes, 0 for no)\n";
cin >> userAnswer;
while (userAnswer != 0)
{
if (curNum == size)
{
p_friends = growArray (p_friends, &size);
}
cout << "What is your friend's name?\n";
cin >> p_friends[curNum].name;
cout << "What is your friend's address?\n";
cin >> p_friends[curNum].address;
cout << "What is your friend's number?\n";
cin >> p_friends[curNum].number;
curNum++;
cout << "Enter another friend? (1 for yes, 0 for no)\n";
cin >> userAnswer;
}
}
FriendInfo *growArray(FriendInfo *p_entry, int *size)
{
*size *= 2;
FriendInfo *p_new_friends = new FriendInfo[*size];
for (int i = 0; i < *size; ++i)
{
p_new_friends[i] = p_entry[i];
}
delete [] p_entry;
return p_new_friends;
}
強制性的問題 - 你爲什麼不使用是'的std :: VECTOR'? – PaulMcKenzie 2014-11-24 17:37:41
@PaulMcKenzie:因爲他正在訓練如何駕駛手動? – Deduplicator 2014-11-24 17:39:02
他明確表示他在練習DMA :) – 2014-11-24 17:46:10