c++ - 尝试运行指针排序算法时出现段错误(核心已转储)

标签 c++ sorting ubuntu segmentation-fault g++

我正在尝试根据与它们关联的字符串为三个指针变量创建排序算法。但是,每次我尝试运行该程序时,在我通过第一个用户数据入口点后,都会抛出段错误(核心转储)错误。我已经在许多网站上查看过这个问题,但未能找到有效的答案。我相信这是我的指针变量的内存分配错误,但我不知道如何修复它或它在哪里。我应该怎么做才能缓解这种情况?这是一些示例代码:

//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/

相关文章:

c++ - 将 char* 数组作为字符串返回 -> 内存泄漏?

objective-c - Objective C - 对字符串数组进行排序

git - 如果没有用户通过控制台登录,ubuntu 上的 Jenkins 无法访问 SSH 文件夹?

python - 如何在 Jupyter 中使用 matplotlib 后端 "TkAgg"

c++ - 使用 Asio (Boost) 通过网络发送灵活数量的数据

c++ - QHttp 在 Qt5 中不可用

javascript - 如何避免使用 2 个条件对 JavaScript 数组进行两次排序

c# - .NET 中对以 1、10 和 2 开头的字符串进行排序并遵守数字顺序的最短方法是什么?

linux - Ubuntu 更新管理器的问题

c++ - 将 Linux system() 调用命令的输出重定向到一个变量