Jose
Jose

Reputation: 3558

Returning an array of 2D arrays in C

First, I'll admit this is homework but it has been around six years since I last programmed in C and ever since I have been only programming in Python and Java.

I want to generate successor 2D arrays to a 2D array for example:

[1][2][3] 
[4][5][6] 
[7][8][ ]

For the 2D array above, the successor 2D arrays would be:

[1][2][3]
[4][5][6]
[7][ ][8] 

and

[1][2][3]
[4][5][ ]
[7][8][6]

This wouldn't be a problem if I just placed the code for this in a main() method.

However I want to separate the code for this part and encapsulate it in a function and just call it when I need it. In other words, I want to generate both arrays from inside a function and return both of them.

In C this is isn't as straightforward because I can't make a function that can pass an array of 2D arrays.

I have some ideas like

  1. return a struct with a 2d array and next variable that is a pointer to another successor 2D array (I want to process all the successor arrays in a loop).

  2. create a global pointer where I will point the head to the first struct, which in turn points to the next succesor 2d array and so on.

But I am not really confident which one to try. Looking for other helpful leads.

Upvotes: 2

Views: 549

Answers (2)

Chris Eberle
Chris Eberle

Reputation: 48795

To return an array of 2D arrays:

int*** getArrayOf2DArrays(int num_arrays, int rows_per_array, int cols_per_array)
{
    int*** arr = malloc(num_arrays * sizeof(int**));
    // check that arr isn't null

    for(int i = 0; i < num_arrays; i++)
    {
        arr[i] = malloc(rows_per_array * sizeof(int*));
        // again, check result

        for(int j = 0; j < rows_per_array; j++)
        {
            arr[i][j] = malloc(cols_per_array * sizeof(int));
            // yet again, check result

            // NOT necessary, but if you want to initialize the values
            // here, you could. Either use memset or:
            for(int k = 0; k < cols_per_array; k++)
                arr[i][j][k] = 0;
        }
    }

    return arr;
}

And then you can access it with arr[array_number][row][col]. Make sure to free it when you're done (similar process, only in reverse):

void freeArrayOf2DArrays(int*** arr, int num_arrays, int rows_per_array)
{
    // sanity checks here
    for(int i = 0; i < num_arrays; i++)
    {
        // and here
        for(int j = 0; j < rows_per_array)
            // and here
            free(arr[i][j]);
        free(arr[i]);
    }

    free(arr);
}

And of course you can just pass this pointer around to any of your functions using a int*** data type.

Upvotes: 3

Vitor
Vitor

Reputation: 2792

An array of 2D arrays is just a 3D array, so you can pass them the same way as parameters/return values. Since you have a fixed size in 2 dimensions, it may be a lot easier to just use a int* as type, and treat it as a 3D array

Upvotes: 1

Related Questions