Sergey Teryan
Sergey Teryan

Reputation: 63

Return a dynamically allocated array? (C)

Consider the given 2d array allocation:

int (*some)[10] = malloc(sizeof(int[10][10]));

This allocates a 10 x 10 2d array. Apparently its type is int (*)[10]. I want to write a function initialize() that will allocate it, initialize it and then return a pointer to the array, so that the construction some[i][j] would be usable in other functions which can pass a pointer to the array it onto each other.

What should the prototype, specifically the return type of initialize() be?

Upvotes: 1

Views: 3348

Answers (3)

mch
mch

Reputation: 9804

int (*initialize(void))[10] { ... }

initialize is a function, which takes no parameters and returns a pointer to an array of 10 int.

You should use a typedef for that.

Upvotes: 7

Petr Skocik
Petr Skocik

Reputation: 60067

In int (*some)[10] = malloc(sizeof *some);, some is a "pointer to an array of 10 int`.

If you want other to be a function returning a pointer to an array of of 10 int, you can start with int (*some)[10]; and replace some with what a call to a such function would look like to get your declaration.

int (*some)[10]; => int (*other(argument1,argument2))[10];

That's how it worked in pre-standardized C. Since standardized C has prototypes, you'd also replace the argument identifier list with a parameter type list, e.g.:

int (*other(int argument1, double argument2))[10];

The cdecl program or the cdecl website can help you verify the result:

$ echo 'explain   int (*other(int,double))[10]'|cdecl
  declare other as function (int, double) returning pointer to array 10 of int

Most people find typedefs more readable:

typedef int (*pointer_to_an_array_of_10_int)[10];
pointer_to_an_array_of_10_int other(int, double);

//to verify it's a compatible declaration 
int (*other(int , double ))[10]; 

Upvotes: 0

0___________
0___________

Reputation: 67584

allocates the table of nrow pointers to (allocated) int array of size elements

void *allocate_rows(int *(*ptr)[size], size_t nrows)
{
    int (*tmpptr)[size] = *ptr;

    *ptr = malloc(nrows * sizeof(*ptr));

    if(*ptr)
    {
        while(nrows--)
        {
            tmpptr = malloc(sizeof(*tmpptr));
            if(!tmpptr)
            {
                /* malloc failed do something */
            }
            else 
            {
                tmpptr++;
            }
        }
    return *ptr;
}

Upvotes: 0

Related Questions