【问题标题】:Is it possible to allocate array inside function and return it using reference?是否可以在函数内部分配数组并使用引用返回它?
【发布时间】:2012-10-23 21:44:00
【问题描述】:

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

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

感谢您的建议

【问题讨论】:

  • 我很久以前就给自己定了一条规则,如果我的代码在任何地方都有***,我必须重写它。
  • 我听说过这个规则,但是在这种情况下,***将节省创建一个只会被调用一次的函数。
  • 不,这并不意味着重新编码,而是意味着重新设计您的数据结构,以便您不需要所有这些间接层。
  • 你应该使用(**list)[i]=123而不是(**list)[count]=123
  • 义务“三星级程序员”笑话:webcache.googleusercontent.com/…

标签: c arrays pointers allocation


【解决方案1】:

你所说的列表实际上是一个数组。你可以这样做:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我没有检查 malloc 是否失败
    【解决方案3】:

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

    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
    

    【讨论】:

    • 哦,我没看到。但问题是:如何分配一维数组并使用引用返回?
    • @Grant 引用是指return &amp;array 还是什么?
    • 使用引用是指作为输出参数。
    • @Grant for (i to n)
      (**list)[i] = new int[desired_length_of_each_array]
      for (k to m)
      (* list)[k] = desired_value
      但我假设您这样做是为了学习 c 语法。因为使用三元组指针不是一种好的编程风格,因为语法非常混乱。主题:顺便说一下,我是这个论坛的新手,我想学习如何在评论中输入新行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2011-07-30
    • 2020-02-23
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多