Can array size or index be passed to a function along with the array in c?

Viewed 63

I want to pass an array among one of the subarrays of an array to a function in C. This is how the function call looks like:

func(arr[cnt][]);

and the function has a syntax like this:

int func(int* arr[x][])
{
//function body
}

Since I am getting quite a lot of errors I was curious to know whether this is possible.Also what should I be taking care of while passing arrays(here:2-dimensional)

2 Answers

No you can not pass the array size as part of the array but you are able to pass it as a second parameter while using array decay. In C, it is very common to let a 2-D array decay into a pointer-to-pointer.

/* arr is an array of 6-element-arrays, max_arrays is the number of arrays in arr */
int func(int *arr[6], size_t max_arrays);

alternatively

struct array {
    /* points to array[6] */
    int (*data)[6];
    size_t num_arrays;
};


int array_data[5][6] = {0};

struct array array1_desc =
{
    .data = array_data,
    .num_arrays = 5
};

int func(struct array *array){
    assert(array != NULL);

    int a = 4;
    int b = 5;

    assert(a < array->num_arrays);
    assert(b < 6);


    /* access one element */
    array->data[a][b] = 0;

    return 0;
}

int main(int argc, char *argv[])
{
    /* array descriptor direct assignment */
    struct array array2_desc;

    array2_desc = array1_desc;

    func(&array1_desc);
    func(&array2_desc);


    return 0;
}

If you pass the dimensions of the array as additional parameters, you can use those as the dimensions of the array parameter. For example:

int func(int x, int y, int arr[x][y])
{
   ...
}

And you would call it like this:

int arr[4][5];
int rval = func(4, 5, arr);
Related