C++: Having troubles with functions and dynamic memory allocation (heap)

http://pastebin.com/Y1n51yKC - Full source
http://pastebin.com/D8kN7wDa - The gist of it


My program undergoes a run-time error every time I uncomment l70-72(1). It's not the first time I encountered this particular problem. I asked my C++ instructor about this, but it had been for over 3 weeks now and she is yet to give me any feedback.

(1)When I call manage_Rectangle_arr(string strCommand, Rectangle * *arr, short *siArrayL) with any of the following: "fill array", "get areas" and "empty contents" (obviously the last two are related to "fill array" in nature, since they need it to be executed first in order to function)

Last edited on
void manage_Rectangle_arr(string strCommand, Rectangle * *arr, short *siArrayL)
modifying arr inside manage_Rectangle_arr does not affect the variable you fed to the function. It will retain the junk it had in it prior to the "make array" call when you call the functions that are barfing on you.

If you insist on this silly method of object management, I suggest you pas by reference. Why on earth are you using a pointer for siArrayL?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void manage_Rectangle_arr(string, Rectangle**&, short);
 
int main()
{
    Rectangle * * arr;
    short siArrayL=1;
 
    manage_Rectangle_arr("make array", arr, siArrayL);
    manage_Rectangle_arr("fill array", arr, siArrayL); //Problem here
    manage_Rectangle_arr("get areas", arr, siArrayL); //Problem here
    manage_Rectangle_arr("empty contents", arr, siArrayL); //Problem here
    manage_Rectangle_arr("delete array", arr, siArrayL);
}

void manage_Rectangle_arr(string strCommand, Rectangle ** & arr, short siArrayL)
{
    if(strCommand=="make array")
    arr = new Rectangle * [ siArrayL];
 
    if(strCommand=="fill array") //Problem here
    for(short s=0; s< siArrayL; ++s)
    arr[s]= new Rectangle(1, 1);
 
    if(strCommand=="get areas") //Problem here
    for(short s=0; s< siArrayL; ++s)
    cout << arr[s]->getArea();
 
    if(strCommand=="empty contents") //Problem here
    for(short s=0; s< siArrayL; ++s)
    delete arr[s];
 
    if(strCommand=="delete array")
    delete [] arr;
} 
"silly method"? Having illusions de grandeur? If so, offer a by-reference-free alternative to my "silly methods".
Last edited on
I should've said naive.

I'll have to pass on doing your homework.
Topic archived. No new replies allowed.