0

I am trying to make 2x2 array, initialize it to 0, and pass it to functions.

I have tried initializing it with

int array[2][2] = {0}

but only the first 5 values come out as 0.

A bigger problem for me is passing the array to a function.

A 2 dimensional array is a pointer to pointers right? So I should be able to pass it as;

function(**array);

Is this correct?

When I try to access this array in the function can I access it in the format of

void function (int **array){
    array[0][2] = choice
}

as this does not work and I assume somewhere I have to define the size of the array.

Thanks.

0x41414141
  • 364
  • 3
  • 16

1 Answers1

6

"A 2 dimensional array is a pointer to pointers right?" – wrong. A 2 dimensional array is just that – a 2 dimensional array; that is, an array of one-dimensional arrays.

If you want to pass a 2x2 array to a function, use a pointer to a 2x2 array:

static void function (int (*array)[2][2]){
    //(*array)[0][2] is out of bounds...
    (*array)[1][0] = 3;
}

int main(void) {
    int array[2][2] = {{0}};
    function(&array);
    return 0;
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • 1
    As an alternative to passing an `int(*)[2][2]`, it is often useful and convenient to pass an `int(*)[2]`, so that you can use `array[i][j]` in the function. The call would here be `function(array);`, and the prototype `static void function(int (*array)[2]);`. – Daniel Fischer Apr 14 '13 at 12:39
  • @DanielFischer: Good point. Similarly for one-dimensional arrays, it can be convenient to pass an `int*` rather than an `int(*)[2]`, to allow more convenient notation and variable array lengths. – Mankarse Apr 14 '13 at 12:40