QUESTION: Hello! I’d like to ask a scope question if you have time. I have a function (function A) that creates an array of objects of type MyClass. Everything works great but I cannot access this array with my other functions. In order to make this array available I need to give it global scope (define it outside of any other function). However, I cannot do that either because once I declare an array outside the functions, I cannot later allocate it dynamically inside a function. So, I have a scope problem. I also tried to declare a pointer outside of functions like this:
extern MyClass *myArray;
and then within my function A I declare my array like this
This, surprsisingly, makes it possible for the other functions of the program to recognize myArray as a legitimate thing but creating a pointer like this (when done by a function other than function A) will never work:
This should work because when I do this in the function A, everything works.
What do you think I’m doing wrong? Thank you for finding the time to help me!! - eric
I would use dynamic allocation. Although you *can* do what you want to do, it's not a good practice. So I won't show you how. :-) The better way to do it is:
extern MyClass *myArray;
// This must be used after the next function
myArray = new MyClass;
Somewhere before the program exits, you must do:
delete  myArray; // free memory for myArray
---------- FOLLOW-UP ----------
QUESTION: Thanks for your answer.
I changed how I declare the array of objects. Now I declare the array locally in a function and when another function operates on it, I pass the array as an argument. This works most of the time but sometimes I get weird problems. It seems that the functions that are executed earlier are affected by functions that aren't even executed yet. This is typically a sign of memory management problems. May I ask you the following question:
What is the difference between declaring an array of objects like this:
MyClass *array=new MyClass;
Only the latter compiles for my program but executes with errors.
So, a simplified version of what I'm trying to do is this:
void MyClass::modifyArray(MyClass *array)
//this modifies array elements permanently
My h_file.h contains this row:
void modifyArray(class MyClass *array);
Thanks again! I hope you are having a nice weekend!
Ok. Some things:
This is an array of pointers to MyClass. Just pointers - the objects are not created.
This would work:
But because these are local, you should not do this because of the potential of stack. You can do this to prevent that:
static MyClass array;
And you want this too:
void MyClass::modifyArray(MyClass array)
Thank you! So far the weekend is nice - I hope the same for you!