4

我试过使用三重指针,但它一直失败。代码:

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

感谢您的任何建议

4

3 回答 3

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;
}
于 2012-11-03T11:43:28.833 回答
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;
}
于 2012-11-03T11:44:54.697 回答
1

你有一个整数数组的数组。让我们仔细看看你的 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
于 2012-11-03T11:32:06.870 回答