我在 push_back() 函数中运行我的代码时出现段错误, 我的程序如下..
程序:
#include<iostream>
#include <vector>
using namespace std;
class Point
{
private:
int x, y;
int * p;
public:
Point(int x1, int y1) {
x = x1; y = y1;
*p = 1;
}
Point(const Point & p2) {
x = p2.x;
y = p2.y;
*p = 1;
}
};
int main()
{
Point p1(10, 15);
Point p2 = p1;
vector<Point> vec;
for (int i=0; i<10; i++)
{
vec.push_back(p2);
}
}
有人可以给出上述程序中出现段错误的原因吗???? 有人可以给出上述程序中出现段错误的原因吗????
最佳答案
Point(int x1, int y1) {
x = x1; y = y1;
*p = 1; <<< allocate memory for this pointer first.
}
您正在取消引用未初始化的指针。
关于c++ - push_back() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215414/