0

Cの関数から1000個の変数を返す方法は?
これは私が答えることができなかったインタビューの質問です.

ポインターの助けを借りてそれを行うことができると思います。私はポインターを初めて使用します.Cは、ポインターまたは別のアプローチを使用してこの問題を解決するための解決策を教えてくれますか?

4

4 に答える 4

3

それらをすべて構造体にパックし、構造体を返します。

struct YourStructure
{
    int a1;
    int b2;

    int z1000;
};

YouStructure doSomething();
于 2012-08-20T10:59:21.607 に答える
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;
}
于 2012-08-20T11:06:09.333 に答える
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呼び出し元が解放する必要があります。


3 番目のアプローチ: 静的メモリ。myfunc2静的メモリを使用して呼び出します。

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

その場合、メモリを割り当てたり解放したりする必要はありません。

于 2012-08-20T11:02:00.487 に答える
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);

代わりは。

于 2012-08-20T11:14:50.860 に答える