我是C++的新手,正在尝试使用动态内存来创建一些基本对象。 我传递一个int参数给一个方法,它正在改变全局变量的值。我认为这与我为新对象分配内存的方式有关,我无法用其他方式编译它。Seg Fault - 将变量传递给方法更改全局值
int main() {
int inp;
CRectangle rectb (2,2);
cout << "enter number of items to add" << endl;
cin >> inp; // let's say inp = 7
rectb.addItemsArray(inp);
cout << "inp after adding items: " << inp << endl; // inp is now 1.
}
头文件:
class CRectangle {
int width;
int height;
item *items[]; // SOLUTION: change this line to "item *items"
int input;
public:
CRectangle (int,int);
int addItemsArray(int);
int area() { return (width*height); }
int get_items(int);
};
- 和 -
class item {
int foo;
char bar;
public:
//SOLUTION add "item();" here (a default constructor declaration without arguments)
item (int, char);
int get_foo();
char get_bar();
};
方法:
int CRectangle::addItemsArray(int in) {
cout << "value of in at begginning:" << in << endl; //in = 7
int i;
i = 0;
//SOLUTION: add "items = new item[in];" on this line.
while (i < in) {
items[i] = new item(1, 'z'); //SOLUTION: change this line to "items[i] = item(1, 'z');"
i++;
}
cout << "value of in at end " << in << endl; //in = 7
return 1;
}
有时我得到一个总线错误或赛格故障。有时它可以像预期的那样使用较低的数字,如2或3,但并不总是如此。
任何帮助将不胜感激。
编辑(CRectangle的构造函数):
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
(项目的构造函数):
/* SOLUTION add default item constuctor
item::item() {
foo = 0;
bar = 'a';
}
*/
item::item(int arg, char arg2) {
foo = arg;
bar = arg2;
}
难道您发布CRectangle的构造函数的实现? – Erwald 2012-04-17 13:48:53
是的,我们需要看看它是如何初始化“items”的。 (为什么不使用类似'vector'的东西来为你做所有这些事情?) – 2012-04-17 13:49:22
没有这个类的其他代码,很难知道什么是错的。不过,我的第一个猜测会与你的物品数组有关。你是否曾经(重新)分配空间来记录指向新项目的指针? – atk 2012-04-17 13:50:13