我是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