【发布时间】:2014-11-24 17:35:00
【问题描述】:
我是 C++ 新手(从我的代码中可以看出),我正在练习使用指针和数组以及我的结构进行动态内存分配。我的代码工作正常,直到它访问“growArray”函数,然后它给了我 SIGSEGV 错误。我不知道为什么,因为据我所知,我正确地传递了一个指向指针的指针,而且我还为新指针分配了空间。是我的结构有问题,还是传递指针有问题,还是接收指针有问题?我希望这个问题有意义。
#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:因为他正在训练如何手动驾驶?
-
他确实明确表示他正在练习 DMA :)
标签: c++ arrays pointers function-pointers dynamic-programming