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

2024-04-10

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

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

感谢您的任何建议


你所说的列表实际上是一个数组。您可以按照以下方式进行操作:

#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐