tags:

views:

4539

answers:

4

Does someone know how can I use multi-dimesional arrays using C? Is that possible?

Thanks a lot...

A: 
int x[5][4];

Creates a 5x4 array of ints, for example.

Then, x[0] returns the first row, and x[0][3] returns the first row, last column.

Marquis Wang
It's static array.
klew
+4  A: 

With dynamic allocation, using malloc:

int** x;

x = (int**)malloc(dimension1_max * sizeof(int*));
for (int i = 0; i < dimension1_max; i++) {
  x[i] = (int*)malloc(dimension2_max * sizeof(int));
}

[...]

for (int i = 0; i < dimension1_max; i++) {
  free(x[i]);
}
free(x);

This allocates an 2D array of size dimension1_max * dimension2_max. So, for example, if you want a 640*480 array (f.e. pixels of an image), use dimension1_max = 640, dimension2_max = 480. You can then access the array using x[d1][d2] where d1 = 0..639, d2 = 0..479.

But a search on SO or google also reveals other possibilities, for example in this SO question

Note that your array won't allocate a contiguous region of memory (640*480 bytes) in that case which could give problems with functions that assume this. So to get the array satisfy the condition, replace the malloc block above with this:

int** x;
int* temp;

x = (int**)malloc(dimension1_max * sizeof(int*));
temp = (int*)malloc(dimension1_max * dimension2_max * sizeof(int));
for (int i = 0; i < dimension1_max; i++) {
  x[i] = temp + (i * dimension2_max);
}
schnaader
This won't compile, you need to declare x as "int **", not "int[][]".
Adam Rosenfield
What does this exactly do? What is dimension1_max and dimension2_max?What does the first "for"?
rpf
Thanks, Adam, I knew something was wrong although I already corrected the first sizeof to int* instead of int.
schnaader
It is not a multidimensional array - it is array of pointers to int, or array of arrays. To allocate memory for real 2D array you need to use malloc(dim1 * dim2 * sizeof(int)). If some function expects pointer to 2D array, like foo(int * bar[5][6]) and you pass your x, weird things will happen.See http://en.wikipedia.org/wiki/C_syntax#Multidimensional_arrays
qrdl
Ah, I get what you mean. I've added another example where a contiguous region of memory is provided and also corrected the malloc calls that weren't casted to int*/int**.
schnaader
+6  A: 

Basics

Arrays in c are declared and accessed using the [] operator. So that

int ary[5];

declares an array of 5 integers. Elements are numbered from zero so ary1[0] is the first element, and ary1[4] is the last element. Note1: There is no default initialization, so the memory occupied by the array may initially contain anything. Note2: ary1[5] accesses memory in an undefined state (which may not even be accessible to you), so don't do it!

Multi-dimensional arrays are implemented as an array of arrays (of arrays (of ... ) ). So

float ary2[3][5];

declares an array of 3 one-dimensional arrays of 5 floating point numbers each. Now ary2[0][0] is the first element of the first array, ary2[0][4] is the last element of the first array, and ary2[2][4] is the last element of the last array. The '89 standard requires this data to be contiguous (sec. A8.6.2 on page 216 of my K&R 2nd. ed.) but seems to be agnostic on padding.

Trying to go dynamic in more than one dimension

If you don't know the size of the array at compile time, you'll want to dynamically allocate the array. It is tempting to try

double *buf3;
buf3 = malloc(3*5*sizeof(double));
/* error checking goes here */

which should work if the compiler does not pad the allocation (stick extra space between the one-dimensional arrays). It might be safer to go with:

double *buf4;
buf4 = malloc(sizeof(double[3][5]));
/* error checking */

but either way the trick comes at dereferencing time. You can't write buf[i][j] because buf has the wrong type. Nor can you use

double **hdl4 = (double**)buf;
hdl4[2][3] = 0; /* Wrong! */

because the compiler expects hdl4 to be the address of an address of a double. Nor can you use double incomplete_ary4[][]; because this is an error;

So what can you do?

  • Do the row and column arithmetic yourself
  • Allocate in a function
  • Use an array of pointers (the mechanism qrdl is talking about)

Do the math yourself

Simply compute memory offset to each element like this:

  for (i=0; i<3; ++i){
     for(j=0; j<3; ++j){
        buf3[i * 5 + j] = someValue(i,j); /* Don't need to worry about 
                                             padding in this case */
     }
  }

Allocate in a function

Define a function that takes the needed size as an argument and proceed as normal

void dary(int x, int y){
  double ary4[x][y];
  ary4[2][3] = 5;
}

An array of pointers

Consider this:

double **hdl5 = malloc(3*sizeof(double*));
/* Error checking */
for (i=0; i<3; ++i){
   hdl5[i] = malloc(5*sizeof(double))
   /* Error checking */
}

Now hdl5 points to an array of pointers each of which points to an array of doubles. The cool bit is that you can use the two-dimensional array notation to access this structure---hdl5[0][2] gets the middle element of the first row---but this is none-the-less a different kind of object than a two-dimensional array declared by double ary[3][5];.

This structure is more flexible then a two dimensional array (because the rows need not be the same length), but accessing it will generally be slower and it requires more memory (you need a place to hold the intermediate pointers).

Note that since I haven't setup any guards you'll have to keep track of the size of all the arrays yourself.

Arithmetic

c provides no support for vector, matrix or tensor math, you'll have to implement it yourself, or bring in a library.

Multiplication by a scaler and addition and subtraction of arrays of the same rank are easy: just loop over the elements and perform the operation as you go. Inner products are similarly straight forward.

Outer products mean more loops.

dmckee
Just one point - array of arrays is array of pointers, not a real multidimensional array.http://en.wikipedia.org/wiki/C_syntax#Multidimensional_arrays
qrdl
@qrdl: As I read the standard int **a1; and int *a2[i]; int a3[n][m]; are different critters with different semantics. The last one gets allocated a block of continguous (possibly padded) memory without a separate set of intermediate pointers... Try printf("%d\n",sizeof(int[3][5])/sizeof(int));
dmckee
A: 

the demo of int ** does not work nicely for float **.