Search code examples
cmultidimensional-arraymalloctypedeffunction-declaration

Proper return statement and function type


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.


Solution

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