Pointer to an Array Versus an Array of Pointers

Hi, my question is basically the title of the topic. I know that an array of pointers uses scatter chunks of free memory while a pointer to an array uses a stack of free memory, and i know this is an advantage, but i dont fully understand why using an array of pointers is much better.
Ive read that you have to use an array of pointers when you dont know the size of the input array but i dont understand why.
I know that it is not a precise question but any thoughts will be of great help.

Sorry for my english.

Thanks in advance!

I'm sure that's not your real question, as these are 2 completely different things, and the assertions are incorrect.

An array of pointers is simple a collection of pointers, it says nothing about where the pointers have come from, or what type of memory they point to, beyond the fact that they point to different things.

Consider this contrivance

1
2
3
4
5
6
7
8
9
10
int *pa[4]; // array of pointers to int
int v = 0;
int x = 0;
int *y = new int;
int *z = new int;

pa[0] = &v;
pa[1] = &x;
pa[2] = y;
pa[3] = z;

Now you have an array of pointers to int, with some members on the stack and some in the heap.

A pointer to an array on the other hand, is just a pointer. The array itself could be a collection of any type, including pointers.

1
2
3
4
5
int **ap = pa; // pointer to array of pointers

int ia[4] = {0};

int *iap = ia; // pointer to array of ints 


Perhaps you meant to ask about the difference between memory that's been dynamically allocated on the heap versus statically on the stack?

When you know the size of your array up-front you have the option of reserving space for it on the stack at compile time.
If you don't you're forced to request space from the heap at run-time.

If this is the thought you want to explore, then a quick tutorial on the web might help, e.g. http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
Topic archived. No new replies allowed.