【问题标题】:Seg Fault - Passing variable to method changes global valueSeg Fault - 将变量传递给方法会更改全局值
【发布时间】:2012-04-17 13:44:47
【问题描述】:

我是 C++ 的新手,正在尝试使用动态内存创建一些基本的对象。 我将一个 int 参数传递给一个方法,它正在改变全局变量的值。我认为这与我为新对象分配内存的方式有关,我无法让它编译任何其他方式。

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 构造函数的实现吗?
  • 是的,我们需要看看它是如何初始化items的。 (你为什么不使用像 vector 这样的东西来为你做所有这些事情呢?)
  • 没有类的其余代码,很难知道哪里出了问题。但是,我的第一个猜测与您的项目数组有关。您是否曾经(重新)分配空间来记录指向新项目的指针?

标签: c++ pointers dynamic-memory-allocation


【解决方案1】:

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

item *items[];

std::vector<item*> items;

然后向其中添加项目:

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

【讨论】:

  • 或者,为了简单起见,std::vector&lt;item&gt; itemsitems.push_back(item(1, 'z'));
  • 感谢您的帖子。我一直避免使用向量,因为在开始使用字符串和向量等有用的工具之前,我正在尝试学习如何更本机地做事(不使用其他类)。
【解决方案2】:

您好像忘记创建 items 数组了...

您定义了一个动态分配的数组(不是 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');
}

【讨论】:

  • 我添加了“items = new item[100];”到 CRectangle 构造函数,但它不会以这种方式编译。将“item *items [100]”添加到项目声明中,我试图在运行时分配内存。我是否总是必须为数组分配高估 (100)?
  • /*** 我已将我的解决方案编辑到 OP 中。 ***/ 它基本上是您的解决方案 DirkMausF 的修改版本。发送。
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多