Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

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

I've tried using a tripple pointer, but it keeps failing. Code:

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

int set(int *** list) {
  int count, i;
  printf("Enter number:
");
  scanf("%d", &count);
  (*list) = (int **) malloc ( sizeof (int) * count);

  for ( i = 0; i<count;i++ ) {
    (**list)[count] = 123;
  }
  return count;
}

int main ( int argc, char ** argv )
{
  int ** list;
  int count;

  count = set(&list);

  return 0;
}

Thanks for any advice

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:
");
  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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...