user3283146 user3283146 - 1 month ago 4
C Question

Passing a dynamically allocated 2d character array to a function

Here is how the array is allocated.

char** cArray = malloc(10 * sizeof(char *));

int i;
for(i =0; i< 10; i++) {
cArray[i] = malloc(25 * sizeof(char));
}


How to pass into function with this signature:

sampleFunction(int max, char list[][max]){
//Do something
};


Tried:

sampleFunction(25, cArray);


This gives me the following error:

expected 'char (*)[(sizetype)(max)]' but argument is of type 'char **'


I have also tried:

sampleFunction(int max, char* list[][max]){
//Do something
};

sampleFunction(25, &cArray);


This gives me the following error:

expected 'char * (*)[(sizetype)(max)]' but argument is of type 'char ***'


I have also tried:

sampleFunction(int max, char* list[][max]){
//Do something
};

sampleFunction(25, cArray);


This gives me the following error:

expected 'char * (*)[(sizetype)(max)]' but argument is of type 'char **'


What is the correct way to do this?

Answer

Arrays are not pointers, and pointers are not arrays.

The first parameter type says that list is a pointer to an array of char.
cArray isn't; it's a pointer to char*.

The second says that list is a pointer to an array of char*, which is even further from cArray.

You need to pass the correct type, char**, and both dimensions:

void sampleFunction(int max_rows, int max_columns, char** list){
    for (int i = 0; i < max_rows; i++)
        for (int j = 0; j < max_columns; j++)
            list[i][j] = 0;
}

sampleFunction(10, 25, cArray);