Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Dec 4, 1998

Array of pointers.

Question:
I need to pass an array of pointers to a class to a function. The function is: void myFunc(myClass *example[]); The problem is that I need to define the size of this array at run time. I know this is possible with a normal array. For example:

int *array; array = new int[size]; where size is a variable.

Is it possible to set up an array of pointers in this way? If so how is it done?

Answer:
A pointer is simply an integer that is an address of a memory location. So an array of pointers is really no different than an array of integers.

The first change you must make is with the declaration of array. If you were allocating an array of integers, then the array variable would be a pointer to the (first) integer in the array. However, if you want to allocate an array of pointers to integers, then the array variable must be a pointer to the (first) pointer to an integer in the array.

int **array;
Then you can use new as you did before, except the array data type is now integer pointers instead of just integers.
array = new int*[size];
It is very important to note that this does not allocate memory where those pointers will point. It only allocates the array of the pointers.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date