尝试访问指针内的数组时出现分段错误

时间:2013-08-20 08:20:35

标签: c++ pointers segmentation-fault

当我开始运行项目时,我遇到了分段错误。

我已经宣布了两个不同的类

Class myfirstclass {
int x[4];
};

在第二节课

我使用以下

访问数组“x [4]”
myfirstclass  * firstptr;
firstptr -> x[4];

现在我分配了“firstptr - > x [4];“对一个数组进行一些计算我得到了一个分段错误?

int y[4];
for (int i=0; i<4;i++){
  y[i]= firstptr -> x[i]; -> "This statement what caused the segmentation fault."
}

你能帮我解决这个错误吗?

3 个答案:

答案 0 :(得分:1)

如果你这样做

myfirstclass  * firstptr;
firstptr -> x[4];

您尚未初始化firstptr。您需要执行类似

的操作
myfirstclass  * firstptr = new myfirstclass();

不要忘记某处delete firstptr
或者只使用堆栈

myfirstclass  first;

接下来,您正在使用

firstptr -> x[4];

由于您int x[4];有4个项目,因此可以访问x[0]x[1]x[2]x[3]。没有x[4]

注意 - 如果您使用堆栈,请使用.代替->

first.x[i];

答案 1 :(得分:1)

您必须在使用前创建对象。这样的事情:

myfirstclass  * firstptr = new myfirstclass();

或者您应该使用动态分配的对象丢弃

myfirstclass  firstptr;
int y[4];
for (int i=0; i<4;i++){
  y[i]= firstptr.x[i]; -> "This statement what caused the segmentation fault."
}

要访问x,您应该将其公开:

class myfirstclass {
public:
int x[4];
};

实际上,不建议将数据字段用于公共场所。

答案 2 :(得分:0)

你需要分配你的班级。

for循环之前执行:

firstptr = new myfirstclass;