c++ - Segmentation fault (core dumped) while attempting to run a sorting algorithm for pointers
问题描述
I am attempting to create a sorting algorithm for three pointer variables based on the strings that are associated with them. However, every time I attempt to run the program, after I get past the first user data entry point, the Segmentation fault (core dump) error is thrown. I have looked on many sites to research this and have not been able to find an answer that works. I believe it is an error with the memory allocation of my pointer variables, but I have no idea how to fix it or where it is. What should I do to alleviate this? Here is some sample code:
//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;
I am new to Ubuntu and C++, and have only used Java before, so I apologize for any atrocious errors I may have unwittingly made. Thank you in advance for your help!
解决方案
front, middle, end, spare = new Balloon; //allocate storage for these variables.
这仅分配一个Balloon
结构并分配spare
为指向它的指针。没有分配其他指针。要分配所有气球,您需要单独执行每个气球:
front = new Balloon();
middle = new Balloon();
// etc.
如果您打开所有编译器警告,您将收到有关此错误的消息。例如,使用g++
,您可以执行
g++ -Wall <filename>
推荐阅读
- javascript - 是否可以在运行时在 Node.js 中生成带有函数的对象?
- reactjs - 使用 componentDidUpdate 在反应中更新状态
- python - 使用线性回归的时间序列
- java - 休眠中事务中的延迟更新创建问题
- python - 将键多值字符串转换为键值对
- windows - 错误处理程序未捕获 PowerShell 中的错误
- javascript - 如何防止 ajax 表单提交写在任何地方?
- c# - 添加到列表返回 null
- javascript - 使用 querySelector 时的奇怪行为
- javascript - 使用 Bash heredoc 在 Bash 终端中运行 ES6 代码