Hi All
What is the diff between int **p; and int *p[number];
Are they same? I want to allocate memory for array of 10 int
pointers..How can i do this?
The declaration int **p reserves memory for one pointer only. It may
reference another memory location storing a pointer to an int, or an
array of such pointers. This second location is not allocated nor
initialized by declaring p.
You could use it in the following way:
int **p = new int* [10]; // reserve memory for 10 int pointers and
make pp point to it.
for ( int i = 0; i < 10; ++ i ) { // allocate 10 arrays of ints and
assign them to the 10 pointers.
p
= new int [20];
}
In your code you can now use p[0][0] ... p[9][19] as a two-dimensional
table of ints.
I learned this construction under the term "dope vectors".
So what's the difference to the declaration int* p[10] or the
equivalent int p[10][20]?
int* p[10] fixes the number of rows to a compile-time constant, the
space to store the ten pointers is already reserved but not
initialized. int **p may be reassigned later with a differently sized
array of pointers. In both versions you may allocate different row
lengths (number of columns) to each row, for non-rectangular table
sizes (eg. triangular shapes).
int p[10][20] fixes both dimensions, to rectangular shaped tables. The
memory is for the ints is allocated as a single block of 200
locations, each fitting one int.
Depending on the machine architecture, dope vectors may be faster or
slower than single block tables. To resolve a location p[3][5] on a
blocked (monolithic) table, the compilers generate pseudo code that
looks similar to the following:
p[3][5] = 42;
---> final_address = p + ( 3 * 20 + 5 )
---> *final_address = 42
with dope vectors, the syntax written in code is the same, but
translates to a different addressing scheme:
p[3][5] = 42;
---> final_address = *(p + 3) + 5;
---> *final_address = 42;
thus, one multiplication is replaced by an extra memory dereference.
Especially on older machines (Motorola 68000 comes to my mind), this
is cheaper than the multiplication and results in better application
performance. The cost is space for one extra pointer per table row.
mu.