Note that there are some explanatory texts on larger screens.

plurals
  1. POSeg Fault - Passing variable to method changes global value
    primarykey
    data
    text
    <p>I'm a newbie to c++ and am trying to do some basic object creation using dynamic memory. I'm passing an int argument to a method and it is changing the value of the global variable. I think it has something to do with the way I'm allocating memory for new objects, I cant get it to compile any other way.</p> <pre><code>int main () { int inp; CRectangle rectb (2,2); cout &lt;&lt; "enter number of items to add" &lt;&lt; endl; cin &gt;&gt; inp; // let's say inp = 7 rectb.addItemsArray(inp); cout &lt;&lt; "inp after adding items: " &lt;&lt; inp &lt;&lt; endl; // inp is now 1. } </code></pre> <p>header files:</p> <pre><code>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); }; </code></pre> <p>-and-</p> <pre><code>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(); }; </code></pre> <p>method:</p> <pre><code>int CRectangle::addItemsArray(int in) { cout &lt;&lt; "value of in at begginning:" &lt;&lt; in &lt;&lt; endl; //in = 7 int i; i = 0; //SOLUTION: add "items = new item[in];" on this line. while (i &lt; in) { items[i] = new item(1, 'z'); //SOLUTION: change this line to "items[i] = item(1, 'z');" i++; } cout &lt;&lt; "value of in at end " &lt;&lt; in &lt;&lt; endl; //in = 7 return 1; } </code></pre> <p>Sometimes I get a bus error or seg fault. Sometimes it works as expected with lower numbers like 2 or 3, but not always.</p> <p>Any help would be greatly appreciated.</p> <p>Edit (CRectangle's constructor):</p> <pre><code>CRectangle::CRectangle (int a, int b) { width = a; height = b; } </code></pre> <p>(item's constructor):</p> <pre><code>/* SOLUTION add default item constuctor item::item() { foo = 0; bar = 'a'; } */ item::item(int arg, char arg2) { foo = arg; bar = arg2; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload