0

Is it possible to declare a dynamic array in (main), but use malloc inside another function? I mean something like this

.
.
int main(void)
{
    .
    .
    int **array;
    .
    .
}
void function(int **arr)
{
    .
    array = (**int) malloc .......
    .
}

3 Answers3

0

Yes, it is possible but not like you suggest but like this:

int main(void)
{
    .
    int *array;
    function(&array);
    .
}

void function(int **arr)
{
    .
    *array = malloc(..)  // no cast is needed here
    .
}

And your unneeded (**int) cast is wrong, it should be (int*).

Read also this SO article which is almost a duplicate of your question.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Could you please explain why the second ( * ) is unneeded or wrong? I use the double ** because that's the way my professor taught me and I have used it many times –  May 01 '20 at 17:13
  • @Alex745 `(**int)` is syntactically wrong. The `*` needs to ba _after_ the type. And the `**` is wrong for the same reason it is wrong in `int *array = (int**)malloc(...)`. But casting the return value of `malloc` is totally unnecessary anyway. `malloc` returns a `void*` and in C (not in C++) void pointers are safely promoted to any pointer type. – Jabberwocky May 01 '20 at 17:17
0

Yes, receiving a pointer to pointer:

void function(int **array, size_t elements)
{
    *array = malloc(sizeof(int) * elements);
    if (*array == NULL)
    {
        // raise error
    }
}

int main(void)
{
    int *array;

    function(&array, 10);
    return 0;
}

another option is return the address (the allocated space) from the function:

int *function(size_t elements)
{
    int *array = malloc(sizeof(int) * elements);

    if (array == NULL)
    {
        // raise error
    }
    return array;
}

int main(void)
{
    int *array = function(10);

    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

Yes it is possible like this.

int main(void)
{
    int *array;
      function(&array);

}
void function(int **arr)
{
    .
    *arr = (int *) malloc .......
    .
}