Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a multidimensional array of variable size

I'm trying to understand what "best practice" (or really any practice) is for passing a multidimensional array to a function in c is. Certainly this depends on the application, so lets consider writing a function to print a 2D array of variable size. In particular, I'm interested in how one would write the function printArry(__, int a, int b) in the following code. I have omitted the first parameter as I'm not exactly sure what that should be.

void printArry(_____, int a, int b){
/* what goes here? */
}


int main(int argc, char** argv){

int a1=5;
int b1=6;
int a2=7;
int a2=8;

int arry1[a1][b1];
int arry2[a2][b2];

/* set values in arrays */

printArry(arry1, a1, b1);
printArry(arry2, a2, b2);

}
like image 568
ABD Avatar asked Jan 01 '16 19:01

ABD


2 Answers

The easiest way is (for C99 and later)

void printArry(int a, int b, int arr[a][b]){
    /* what goes here? */
}

But, there are other ways around

void printArry(int a, int b, int arr[][b]){
    /* what goes here? */
}

or

void printArry(int a, int b, int (*arr)[b]){
    /* what goes here? */
}

Compiler will adjust the first two to the third syntax. So, semantically all three are identical.

And a little bit confusing which will work only as function prototype:

void printArry(int a, int b, int arr[*][*]);
like image 116
haccks Avatar answered Sep 23 '22 02:09

haccks


This is not really an answer, but extended comment to the OP's comment question, "well you can pass the array without knowing the number of rows with this, but then how will you know when to stop printing rows?"

Answer: generally, you can't, without passing the array size too. Look at this 1-D example, which breaks the array size.

#include <stdio.h>

int procarr(int array[16], int index)
{
   return array[index];
}

int main (void)
{
    int arr[16] = {0};
    printf("%d\n", procarr(arr, 100));
    return 0;
}

Program output (although all elements initialised to 0):

768

That was undefined behaviour and there was no compiler warning. C does not provide any array overrun protection, except for array definition initialisers (although such initialisers can define the array length). You have to pass the array size too, as in

#include <stdio.h>

int procarr(int array[16], size_t index, size_t size)
{
    if (index < size)
        return array[index];
    return -1;                  // or other action / flag
}

int main (void)
{
    int arr[16] = {0};
    printf("%d\n", procarr(arr, 100, sizeof arr / sizeof arr[0]));
    return 0;
}

Program output:

-1
like image 25
Weather Vane Avatar answered Sep 25 '22 02:09

Weather Vane