0

in C programming how to pass a two dimensional array as a argument of a function with both of the index of the array as a variable? Thanks in advance.

1

I find it hard to understand what you mean. It might help if you told us why you have a 2D array and what you want to do with it, what it is you want to pass to a function.

It begins with your definition of a "two dimensional array". There could be several things treated as "2D-Arrays", which are completely different things:

int LENGTH = 5;
int array[LENGTH][LENGTH];

or

int **array = (int**)malloc(LENGTH*sizeof(int*));
for (int i = 0; i < LENGTH; i++) {
    array[i] = (int*)malloc(LENGTH*sizeof(int));
}

(or

int **array = (int**)malloc(LENGTH*sizeof(int*));
array[0] = (int*)malloc(LENGTH*LENGTH*sizeof(int));
for (int i = 1; i < LENGTH; i++) {
    array[i] = array[0] + i*LENGTH*sizeof(int);
}

last one reducing the malloc calls, but being otherwise about identical to second one)

both create an array that can be used as array[i][j], but the first is actually a 1D-array with the several rows stored one after the other (the compiler fakes it, and requires some information for doing so).

First one might be difficult to pass to a function, since the function signature needs to specify all dimensions, only the first one (usually interpreted as "number of rows" in 2D) is optional. There's an article on that on GeeksforGeeks.

Second version is an int**, and to be passed as such. More flexible, less efficient in terms of memory overhead and setup (1D requires one pointer, 2D one for the array, and one per row), but requires no extra knowledge by the compiler. Don't forget to free anything you malloc.

3
  • Actually I am a beginner in C, I wanted to write a c code which took a (m* n) matrix where 'm' and 'n' and also the entries of the matrix will be given at runtime by the user and the job of the program is to verify whether the matrix is identity, uppertriangular and lowertriangular. I wanted to write this code using 3 individual functions which checked for identity,uppertriangular and lowertriangular and these functions should take the two dimensional array as argument ,where this two dimensional array is used to store the entries of the matrix Feb 24 '17 at 13:31
  • With newer C compilers, you should be able to use function signatures like bool isident(int m, int n, double[][n]), as long as you specify the dimensions (only first is optional) before the actual array, that's option 3 in the GeeksforGeeks article.
    – Blauelf
    Feb 24 '17 at 13:42
  • Thank you sir, I got the code now. Feb 25 '17 at 2:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .