是否可以在函数内部分配数组并使用引用返回它?

时间:2012-11-03 11:21:35

标签: c arrays pointers allocation

我尝试过使用三重指针,但它仍然失败。代码:

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

int set(int *** list) {
  int count, i;
  printf("Enter number:\n");
  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;
}

感谢您的任何建议

3 个答案:

答案 0 :(得分:7)

您调用的列表实际上是一个数组。您可以通过以下方式执行此操作:

#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;
}

答案 1 :(得分:4)

据我了解你的问题,你想要返回一个在另一个函数中分配的数组:这是这个的简单版本

#include<stdio.h>
#include<stdlib.h>
int* set(int *list) {
  int count, i;
  printf("Enter number:\n");
  scanf("%d", &count);
  list = (int *) malloc ( sizeof (int) * count);

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

  return list;
}

int main ( int argc, char ** argv )
{
  int *list;
  list = set(list);
  //Use whatever you want to do with that array 
  free(list); // don't forget to free
  return 0;
}

答案 2 :(得分:1)

你有一个整数数组的数组。让我们仔细看看你的集合函数:

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

正如您所看到的,您正在将每个数组对象视为整数值。 那应该是一个嵌套循环:

for (i to n)
    // allocate each array
    for (k to m)
        // assign value for each value of array