Is it possible to allocate array inside function and return it using reference?

What you call list is actually an array. You might do it the following way:

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

ssize_t set(int ** ppList) 
{
  ssize_t count = -1;

  printf("Enter number:\n");
  scanf("%zd", &count);

  if (0 <= count)
  {
    (*ppList) = malloc(count * sizeof **ppList);

    if (*ppList)
    {
      size_t i = 0;
      for (; i < count; ++i)
      {
        (*ppList)[i] = 42;
      }
    }
    else
    {
      count = -1;
    }
  }

  return count;
}

int main (void)
{
  int * pList = NULL;
  size_t count = 0;

  {
    ssize_t result = set(&pList);

    if (0 > result)
    {
      perror("set() failed");
    }
    else
    {
      count = result;
    }
  }

  if (count)
  {
    /* use pList */
  }

  ...

  free(pList);

  return 0;
}

Leave a Comment