Advertisement

Array **

Started by July 16, 2000 04:22 AM
4 comments, last by Jaxks 24 years, 5 months ago
I don´t have new ANSI c++ book so can someone make me clear doing two dimension dynamical arrays. I tried it myself but get strange assertion failures.
An array is just a pointer to a place in memory. A two dimensional array is just an array of arrays ... or rather a pointer to memory, where other pointers to arrays stand.

So, in order to create a dynamic two dimensional rectangular array, try this code

        int **myArray;int x = 10;int y = 10;myArray = new int*[ y ];for(int i=0; i<y; i++){  myArray[ i ] = new int[ x ];}        


You can then access thing like myArray[2][2].

MK42

Edited by - MK42 on July 16, 2000 2:13:42 PM
Advertisement

For dynamic arrays see above. To declare a static 2-dimensional array:

int a[3][4];
Thanks!
hey Dan james what is int[1][1]....;
It´s multidimensional array.
If you have an array:

int array[2][3];

It will be 2 sets of numbers (accesed starting at 0, going to 1), with 3 numbers in them (again, it would be starting at 0... to 2 for accessing).

So, it could also be declared:

    int array[2][3] = {8,9,6},{4,5,2};    


array[0][0] is 8
array[0][1] is 9
array[0][2] is 6

array[1][0] is 4
array[1][1] is 5
array[1][2] is 2

Does that help?

- Goblin
"In order to understand the full depth of mankind, you must first seperate the word into its component parts: 'mank' and 'ind'."
- The Goblin (madgob@aol.com)
As MK42 stated earlier:

To create a two-dimensional array...

int **myArray;
int x = 10;
int y = 10;
myArray = new int*[ y ];
for(int i=0; i{
myArray = new int[ x ];<br>}<br><br><br><br>This is NOT the same as:<br><br>int myArray[10][10];<br><br><br>The former method, in memory, gives you an array of pointers,<br>each of which points to an array of ten ints. These ints are<br>NOT guaranteed to be contiguous in memory.<br><br>The latter method gives you a 10x10 block of contiguous ints. A<br>true 10x10 array.<br><br>MK42 also stated that "An array is just a pointer to a place in<br>memory. A two dimensional array is just an array of arrays …<br>or rather a pointer to memory, where other pointers to arrays<br>stand."<br><br>This is also incorrect. A two dimensional array of ints is<br>simply w by h contiguous ints (where w and h are the dimensions of the array), whereas a two-dimensional array of<br>pointers to ints is in fact an array of pointers to other<br>arrays.<br><br>The only reason foo=myArray[5][5] works in both cases is<br>because of C''s type system. If you don''t believe me, try<br>making an array of ints with MK42''s method and then doing this:<br><br>foo = ((int*)myArray)[4][5];<br><br>and see if you get the right answer…<br><br><br><br><br>

This topic is closed to new replies.

Advertisement