C++/scope?
Expert: Eddie - 6/25/2009
QuestionHello! 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
MyClass *myArray[100];
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:
MyClass *pointer=myArray[5];
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
AnswerHello eric, thank you for the question.
If you want to dynamically allocate your array inside of a multiple functions, you declare a global pointer to the type of the array, like you have done. However, you need to initialize it with the new keyword.
For example:
MyClass *theArray;
void foo()
{
theArray = new MyClass[100];
}
You would also be responsible for deleting that memory elsewhere in your program.
Is there a reason you can't simply pass your array (declared elsewhere, not local to the function) as a parameter into your functionA that you describe?
MyClass theArray[100];
void foo(MyClass array[], int arraySize) // Or you can pass by pointer
void foo(MyClass *array, int arraySize)
// Call the function
foo(theArray, 100);
I prefer the explicit array brackets in the parameter list, as it clarifies that array is expected, and not any other type of pointer.
Let me know if this helps.
Thanks.
- Eddie