Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a two dimensional array of unknown size as method argument

I'm trying to pass a two-dimensional array, which size can be dynamic, as a method argument.

Within the method I'd like to use the array with the general array syntax.

int item = array[row][column];

To pass the array is not possible, so I thought about to use a pointer pointer.

- (void)doSomethingWithArray:(int **)array columns:(int)nColumns rows:(int)nRows
{
   int item = array[n][m];
}

But I get the problem when I try to pass the array as the parameter

int array[numberOfRows][numberOfColumns];

[someObject doSomethingWithArray:array columns:numberOfColumns rows:numberOfRows];

I found a lot of tips & tricks, but somehow nothing really works in the way I would like to use it.

Thanks for help, Eny

like image 819
Enyra Avatar asked May 06 '11 10:05

Enyra


1 Answers

Is objective-c based on C99?

If it is, you can use the "new" syntax that allows you to pass dimension information directly.

#include <stdio.h>

void foo(int rows, int cols, int arr[rows][cols]) {
  printf("%d, %d\n", arr[0][0], arr[1][4]);
}

int main(void) {
  int arr[2][12] = {{1, 2, 3, 4, 5}, {11, 12, 13, 14, 15}};
  foo(2, 12, arr);
}

You can see the code running on ideone.

like image 146
pmg Avatar answered Sep 29 '22 10:09

pmg