Sanfer
Sanfer

Reputation: 413

Returning array (pointer) of 2D array in C

A function dynamically creates an int array whose elements are predetermined to be int[2]. Is there any way to have a function assign values to that array and then return it to the caller.

The below code accomplishes this task but throws warning: initialization from incompatible pointer type [enabled by default]

#include <stdlib.h>
#include <stdio.h>

int *get_values()
{
    int (*x)[2] = malloc(sizeof(int[2])*3);

    x[0][0] = 1;
    x[0][1] = 2;

    x[1][0] = 11;
    x[1][1] = 12;

    x[2][0] = 21;
    x[2][1] = 22;

    return x;   
}

int main()
{
    int (*x)[2] = get_values();

    int i;
    for (i=0; i!=3; i++)
        printf("x[%d] = { %d, %d }\n", i, x[i][0], x[i][1]);
}

I'm aware of the alternative where you dynamically allocate both dimensions, but this is something that I am curious about.

Upvotes: 0

Views: 91

Answers (2)

Paul R
Paul R

Reputation: 212939

Rather than keep repeating the same clunky syntax it can be helpful to define a typedef in cases like this. This makes it easier to declare the correct return type for get_values:

#include <stdlib.h>
#include <stdio.h>

typedef int I2[2];

I2 * get_values(void)
{
    I2 * x = malloc(sizeof(I2) * 3);

    x[0][0] = 1;
    x[0][1] = 2;

    x[1][0] = 11;
    x[1][1] = 12;

    x[2][0] = 21;
    x[2][1] = 22;

    return x;   
}

int main()
{
    I2 * x = get_values();

    int i;
    for (i=0; i!=3; i++)
        printf("x[%d] = { %d, %d }\n", i, x[i][0], x[i][1]);

    free(x);
}

LIVE DEMO

Recommended reading: Don't repeat yourself (DRY).

Upvotes: 7

2501
2501

Reputation: 25752

And this is how it looks without a typedef:

int (*get_values(void))[2]
{  
    return NULL;   
}

Pretty unreadable.

Notice in that function definition, if you replace get_values(void) with x you get: int (*x)[2], which is exactly what the pointer definition looks like.

Upvotes: 4

Related Questions