gsundberg
gsundberg

Reputation: 547

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.

Upvotes: 0

Views: 2501

Answers (2)

tmlen
tmlen

Reputation: 9090

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).

Upvotes: 2

dash-o
dash-o

Reputation: 14432

The 'arrayInput' function takes a pointer to array of pointers. This is different than the 2D array, which is array of array of chars. Assuming that you must keep the prototypes and the data definition, you can create an array of points to match the prototype. However, you will need to know the actual dimensions of inputArray (sample code assumed N, M). Also, the code assume that each element of inputArray is nul terminated.

// Caller Function
// N, M are needed.
    char inputArray[N][M] ;
// Fill inputArray

    // Temporary array, holding pointer to each element
    char *p[N] ;
    for (int i=0 ; i<N ; i++ ) p[i] = inputArray[i] ;
    arrayInput(p) ;

Upvotes: 1

Related Questions