0

I would like to have a function which does the following:

int doFunction(int* nIndex)
{

  //nIndex is a 2-D array of any size.
// I would like to fill this array inside this function.
//Eg: in nIndex[2][3], i would like to put 5.

}

int result;
int myIndex[5][6];

result = doFunction(myIndex);

could someone please help me with two things: 1. is the syntax above correct for function definition requiring a 2-d array of any size? 2. is the syntax ok for when i pass myIndex into the function? 3. How to i fill the array in the function, or how do i access its fields?

thanks.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
Sunny
  • 7,444
  • 22
  • 63
  • 104
  • 2
    I'm sure it's a duplicate of something. Possibly (http://stackoverflow.com/questions/404232/how-do-i-pass-a-reference-to-a-two-dimensional-array-to-a-function) (http://stackoverflow.com/questions/8659304/passing-two-dimensional-array-to-a-function-by-refrence-c-programming), (http://stackoverflow.com/questions/14548753/passing-a-multidimensional-variable-length-array-to-a-function) and tons of others. – phoeagon Feb 19 '13 at 12:09

1 Answers1

0

Declaration and definition:

// either void fill_arr(int arr[][5]) or:
void fill_arr(int arr[3][5])
{
    int i j;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 5; j++) {
            arr[i][j] = 42;
        }
    }
}

Calling:

int arr[3][5];
fill_arr(arr);
  • This works of course, but you are limited to int[3][5] or at most int[][5]... – bash.d Feb 19 '13 at 12:18
  • thanks, but i would like both the array sizes to be variable – Sunny Feb 19 '13 at 12:19
  • @Sunny then, pass in another parameter `len` to be the range of the inner subscription. then access `arr[i][j]` as `arr+(i*len)+j`. If you hate doing so, use [`boost::multi_array`](http://www.boost.org/doc/libs/1_53_0/libs/multi_array/doc/user.html) – phoeagon Feb 19 '13 at 12:22
  • @Sunny What do you mean by variable? Do you want an array of pointers to mallocated memory? –  Feb 19 '13 at 12:23