Proper return statement and function type

Viewed 56

I am experimenting with malloc and I am trying to create a dynamic 2D array, I know the size of the second dimension and I am allocating memory like so:

int (*arr)[SIZE] = NULL;
arr = malloc(sizeof(arr[SIZE]) * 10);

My question is, is it possible place the above code into a function, and return the address of the allocated memory, if so what should the type be?

Edit: I am aware of the other method of allocating and return a pointer to a pointer.

Thanks in advance.

2 Answers

For starters the argument of malloc is confusing

arr = malloc(sizeof(arr[SIZE]) * 10);

It seems you mean

arr = malloc(sizeof( *arr ) * 10);

That is you are trying to allocate dynamically an array of the type int[10][SIZE].

More precisely the record used as an argument in the call of malloc

arr = malloc(sizeof(arr[SIZE]) * 10);

is correct but very confusing. It is better not to use such a record for the sizeof operator.

The function declaration can look like

int ( *allocation( size_t n ) )[SIZE];

Or you can introduce a typedef name like

typedef int ( *Array2D )[SIZE];

and then declare the function like

Array2D allocation( size_t n );

where n corresponds to the used by you value 10. That is using the parameter you can specify any number for the array dimension apart from 10.

The allocation size sizeof(arr[SIZE]) * 10 is incorrect but will evaluate to the expected size by coincidence. It should be sizeof(*arr) * 10, meaning 10 times the size of whatever arr points to, in this case arrays of SIZE int.

You can encapsulate this allocation in a function this way:

int (*allocate2D(size_t n))[SIZE] {
    int (*arr)[SIZE] = malloc(sizeof(*arr) * n);
    return arr;
}

Or better:

int (*allocate2D(size_t n))[SIZE] {
    return calloc(sizeof(int[SIZE]), n);
}
Related