Handling entries in 2d vectors

Dear all
How to define the proper entries in a 2D (and +D) vector ?

This is a simple example.

I want sth like this:
1 2 3
4 5 6
7 8 9

I tried with this (I use new since I am modifying a larger code with this structure) [I compile with g++ and it does not complain]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdio.h"
#include "math.h"
#include <new>

int main() {
   int *species;

   species = new int[3,3];

   int i, j;
   int k;

   // initialize to zero
   for (int istampa=0; istampa<3; istampa++) 
      printf("%d , %d , %d\n",species[istampa,0], species[istampa,1], species[istampa,2]);
   printf("\n\n\n");


   k = 0;
   for (i=0; i<3; i++){
       for (j=0; j<3; j++) {
           k++;
           printf("i,j,k = %d,%d,%d\n",i,j,k);
           species[i,j] = k;
    // check after every cycle
   for (int istampa=0; istampa<3; istampa++) 
      printf("%d , %d , %d\n",species[istampa,0], species[istampa,1], species[istampa,2]);
   printf("\n");
       }
   }

   delete species ;

  return 0;
}

This gives at the end :
7 , 8 , 9
7 , 8 , 9
7 , 8 , 9

And the first print is
i,j,k = 0,0,1
1 , 0 , 0
1 , 0 , 0
1 , 0 , 0

that is, the command species[i,j] = k is modified the entire column of j and not a single element.

How can I modify just a single element if I need to use new command ?
Thank you very much in advance .
Bests
Dany77
species = new int[3,3]; is equivalent of species = new int[3];

species[i,j] = k; is quivalent of species[j] = k;

Read about comma operator:
http://en.wikipedia.org/wiki/Comma_operator
http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work

Correct way to declare multidimensional array is: int arr[3][3];
However it will not work with dynamic allocation, you will need to do something like that:
1
2
3
4
unsigned rows = 3, columns = 3;
int** arr = new int*[rows];
for(unsigned i = 0; i < rows; ++i)
    arr[i] = new int[columns];
Last edited on
Topic archived. No new replies allowed.