Search code examples
cfunctionpointersmultidimensional-arraypass-by-reference

Passing a 2D array as a double pointer in C


How would I go about passing a 2D array to the following function

arrayInput(char **inputArray)

and then be able to access the array using standard 2D array syntax

inputArray[][]

Specifically, I need to be able to call atoi(inpuArray[0]) to convert an array of characters to an int. I know that this in not the best way, but it is a project requirement to make it work this way.


Solution

  • In this case, it would not be a 2D array of char, but an array of char* pointers. Like this:

    void arrayInput(char **inputArray) {
        printf("%s\n", inputArray[0]);
        printf("%s\n", inputArray[1]);
    }
    
    int main() {
        char* strings[] = { "hello", "world" };
        arrayInput(strings);
    }
    

    The type of strings is of type char*[] (array of pointer to char), which decays to char** (pointer to pointer to char).

    --

    For a true 2D array, where the rows are concatenated in the same memory buffer, the dimension of the second row needs to be part of the type. For example

    void arrayInput(int mat[][2]) {
        printf("%d %d\n", mat[0][0], mat[0][1]);
        printf("%d %d\n", mat[1][0], mat[1][1]);
    }
    
    int main() {
        int mat[][2] = { {1, 2}, {3, 4} };
        arrayInput(mat);
    }
    

    Here mat is of type int[2][2], which decays to int[][2] (array of array of 2 int) and int(*)[2] (pointer to array of 2 int).