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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: