如何从C中的函数返回1000个变量?

时间:2012-08-20 10:57:33

标签: c

如何从C中的函数返回1000个变量? 这是一个我无法回答的面试问题。

我想在指针的帮助下我们可以做到这一点。我是新手指针和C,任何人都可以使用指针或不同的方法给我解决方案来解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

将它们全部打包在一个结构中并返回结构。

struct YourStructure
{
    int a1;
    int b2;

    int z1000;
};

YouStructure doSomething();

答案 1 :(得分:1)

如果它是相同类型的1000倍(例如int):

void myfunc(int** out){
  int i = 0;
  *out  = malloc(1000*sizeof(int));
  for(i = 0; i < 1000; i++){
    (*out)[i] = i;
  }
}

此函数为1000个整数(整数数组)分配内存并填充数组。

该函数将以这种方式调用:

int* outArr = 0;
myfunc(&outArr);

outArr占用的内存必须在使用后释放:

free(outArr);

看到它在ideone上运行:http://ideone.com/u8NX5


备用解决方案:让调用者完成工作并将数组大小传递给函数,而不是让myfunc为整数数组分配内存:

void myfunc2(int* out, int len){
  int i = 0;
  for(i = 0; i < len; i++){
    out[i] = i;
  }
}

然后,就这样称呼:

int* outArr = malloc(1000*sizeof(int));
myfunc2(outArr, 1000);

同样,调用者必须释放outArr的内存。


第三种方法:静态记忆。使用静态内存调用myfunc2

int outArr[1000];
myfunc2(outArr, 1000);

在这种情况下,不必分配或释放内存。

答案 2 :(得分:1)

数组指针方法:

int * output(int input)
{
    int *temp=malloc(sizeof(int)*1000);
    // do your work with 1000 integers
    //...
    //...
    //...
    //ok. finished work with these integers
    return temp;
}

结构指针方法:

struct my_struct
{
    int a;
    int b;
    double x;
    ...
    //1000 different things here
    struct another_struct;
}parameter;


my_struct * output(my_struct what_ever_input_is)
{
    my_struct *temp=malloc(sizeof(my_struct));
    //...
    //...
    return temp;
}

答案 3 :(得分:0)

这就是你在C中的表现。

void func (Type* ptr);
/*
   Function documentation.
   Bla bla bla...

   Parameters
   ptr      Points to a variable of 'Type' allocated by the caller. 
            It will contain the result of...

*/

如果您打算不通过“ptr”返回任何内容,那么您就会写

void func (const Type* ptr);

代替。