7

How can I pass a multidimensional array to a function in C/C++ ?

The dimensions of array are not known at compile time

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
user380731
  • 89
  • 1
  • 1
  • 4
  • @GMan- If the array was dynamically allocated with sizes based on user input, then the size would not be known at compile-time. – bta Jul 01 '10 at 15:06

9 Answers9

9

A pointer to the start of the array along with the dimensions - then do the array arithmetic in the function is the most common solution.

Or use boost

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
3

Passing the array is easy, the hard part is accessing the array inside your function. As noted by some of the other answers, you can declare the parameter to the function as a pointer and also pass the number of elements for each dim of the array.

#define xsize 20
#define ysize 30
int array[xsize][ysize];
void fun(int* arr, int x, int y)
{
 // to access element 5,20
 int x = arr[y*5+20];
}

fun(array, xsize, ysize);

Of course, I've left out the whole business of allocating the array (since it isn't known what its size will be, you can't really use #defines (and some say they're bad anyhow)

Tom
  • 776
  • 1
  • 5
  • 12
1

Use a vector of vectors, you can pass a vector.

thomasfedb
  • 5,990
  • 2
  • 37
  • 65
  • This is inefficient, except for jagged array (where each row may have a different length from another), or when the elements are strings, etc. Also, in case the asker is looking for variable number of dimensions (which we don't know yet) vectors wouldn't solve that problem because vectors are typedef'ed. – rwong Jul 01 '10 at 15:30
1

You could pass a pointer and sizes, or use a std::vector. But the "real" solution is with a template:

template <size_t N, size_t M>
void foo(int (&pArray)[N][M]);

This function template accepts a N by M array of ints, by reference. Note this is a function template, not a function, so you do get a different instantiated function per array type.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
1

I think this is a GCC extension (or a quite modern C feature), but it can be quite convenient:

void foo(int bar[n][m], int n, int m) {...}
fortran
  • 74,053
  • 25
  • 135
  • 175
  • Don't you have to provide constant values for n and m at compile time? You do on my C++Builder 2010. (Per the question, the dim's are unknown at compile. – Tom Jul 01 '10 at 05:41
1

You can pass the pointer to initial memory location of your multi dimension array. you should also pass the size of array i.e. limit of each dimension.

i.e

int var [x][y][z];
func (var, x, y, z);

function definintion:

void func (int*, int, int, int);
Kumar Alok
  • 2,512
  • 8
  • 26
  • 36
0

I'm just summarizing the options from other posts.

If the number of dimensions (the N as in N-dimensional array) is unknown, the only way is to use a C++ multidimensional array class. There are several publicly available implementations, from Boost or other libraries. See Martin Beckett's post.

If the number of dimensions is known but the array size is dynamic, see Tom's answer for accessing an array element (converting multi index into element pointer). The array itself will have to be allocated with malloc or new.

If you are writing the multidimensional array class yourself, you'll need to know about Row-major-order, Column-major-order, etc.

Namely, if the array dimensios is (Size1, Size2, Size3, ..., SizeN), then:

  • The number of elements in the array is (Size1 * Size2 * Size3 * ... * SizeN)
  • The memory needed is sizeof(value_type) * numOfElements
  • To access the element (index1, index2, index3, ..., indexN), use
    • ptr[ index1 + (Size1 * index2) + (Size1 * Size2 * index3) + ... ] assuming the first array index is the fastest-moving dimension
Community
  • 1
  • 1
rwong
  • 6,062
  • 1
  • 23
  • 51
  • index1 + (Size1 * index2) + (Size1 * Size2 * index3) + ... is better written as i1 + size1 * (i2 + size2 * (... ) ) ...) – Alexandre C. Jul 01 '10 at 15:04
  • @Alexandre: Agree. I'm aware of http://en.wikipedia.org/wiki/Horner_scheme. I just want to show the formula in a way that can be written into a loop etc. – rwong Jul 01 '10 at 15:23
  • sorry, i mean "mathematically". – rwong Jul 01 '10 at 15:31
0

Section 3.4 on this page addresses your question:

http://www.programmersheaven.com/2/Pointers-and-Arrays-page-2

Of course variable-length arrays were not present in C until C99 and as far as I know they are not present in C++. Also, MSVC does not implement/support C99.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
0

A simple method is to flatten the array and iterate using dimensions.

#include <stdio.h>

void print_array(int *arr,int row,int col)
{
     int i,j;
     for(i=0;i<row;i++){           
         for(j=0;j<col;j++){
             printf("%d ",*(arr+i*col+j));
         }
         printf("\n");
     }
}

int main()
{
int a[2][3] = {{1,0,2},{-1,3,1}};
int b[4] = {1,2,3,34};
print_array(a,2,3);
return 0;
}

This technique works but flattening array might prevent compiler optimizations which in turn might result in slow execution.

Sandeep
  • 28,307
  • 3
  • 32
  • 24