2012-04-17 120 views
1

我是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; 
} 
+0

难道您发布CRectangle的构造函数的实现? – Erwald 2012-04-17 13:48:53

+0

是的,我们需要看看它是如何初始化“items”的。 (为什么不使用类似'vector'的东西来为你做所有这些事情?) – 2012-04-17 13:49:22

+0

没有这个类的其他代码,很难知道什么是错的。不过,我的第一个猜测会与你的物品数组有关。你是否曾经(重新)分配空间来记录指向新项目的指针? – atk 2012-04-17 13:50:13

回答

1

看起来你忘了创建项目阵列...

您定义了一个动态分配数组(不是item * items [100],而是item * items [])。之前,你可以使用数组,你必须分配内存来存放物品:

items = new item[100]; 

不要忘记在结束与

delete [] items; 

将其删除。 ;)

代替

int i; 
i = 0; 
while (i < in) { 
    items[i] = new item(1, 'z'); 
    i++; 
} 

而且我会用

for (int i=0; i<in; i++) 
{ 
    items[i] = new item(1, 'z'); 
} 
+0

我加了“items = new item [100];”到CRectangle构造函数,但它不会以这种方式编译。将“item * items [100]”添加到items声明中,我试图在运行时分配内存。我是否总是必须为阵列分配一个高估(100)? – user1034772 2012-04-17 14:18:40

+0

/***我已将我的解决方案编辑到OP中。 *** /它基本上是您的解决方案的修改版本,DirkMausF。 TX。 – user1034772 2012-04-17 15:23:25

4

的问题是,你有没有为您分配投入items指针任何存储。我建议改变:

item *items[]; 

std::vector<item*> items; 

,然后将项目添加到它:

items.push_back(new item(1, 'z')); 
+0

或者,为了简单起见,可以使用'std :: vector items'和'items。push_back(item(1,'z'));'。 – 2012-04-17 14:00:51

+0

感谢您的帖子。我避免使用向量,因为我试图在开始使用有用的工具(如字符串和向量)之前学习如何在本地更多地使用(不使用其他类)。 – user1034772 2012-04-17 14:05:39