我正在尝试根据与它们关联的字符串为三个指针变量创建排序算法。但是,每次我尝试运行该程序时,在我通过第一个用户数据入口点后,都会抛出段错误(核心转储)错误。我已经在许多网站上查看过这个问题,但未能找到有效的答案。我相信这是我的指针变量的内存分配错误,但我不知道如何修复它或它在哪里。我应该怎么做才能缓解这种情况?这是一些示例代码:
//new data type
struct Balloon{
string message=""; //give the balloon object a message and a color
string color="";
};
/// main program
int main (void) {
//Instantiate three Balloon objects.
Balloon *front, *middle, *end, *spare;
front, middle, end, spare = new Balloon; //allocate storage for these variables.
//Ask the user what the messages and colors of the balloons are, and set those values to the pointer variables.
//first balloon
cout << "First balloon text: ";
cin >> front->message; //here is when the error is thrown
cout << "Color: ";
cin >> front->color;
我是 Ubuntu 和 C++ 的新手,之前只使用过 Java,所以对于我可能无意中犯下的任何严重错误,我深表歉意。预先感谢您的帮助!
最佳答案
front, middle, end, spare = new Balloon; //allocate storage for these variables.
这只会分配一个Balloon
结构并将spare
分配为指向它的指针。没有分配其他指针。要分配所有气球,您需要单独分配每一个:
front = new Balloon();
middle = new Balloon();
// etc.
如果您打开所有编译器警告,您将收到有关此错误的消息。例如,使用 g++
,你可以做
g++ -Wall <filename>
关于c++ - 尝试运行指针排序算法时出现段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58193434/