C++/scope?

Advertisement


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



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  

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2012 About.com, a part of The New York Times Company. All rights reserved.