C程序返回数组

1 c

我正在开发一个非常基本的程序,我希望将一个长度为2的整数数组返回到我的主程序块.我不能让它工作,我被告知我可能需要指针来做这件事.指针如何工作,我如何在我的程序中使用它?这是我目前的代码:

int[] return2();


int main() {

  int a[2];

  a = request();
  printf("%d%d\n", a[0], a[1]);


  return(0);
}

int[] request ()
{
  int a[2];

  a[0] = -1;
  a[1] = 8;

  return a;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 6

  • 您不能声明返回数组的函数.

    ISO/IEC 9899:1999

    §6.9.1函数定义

    3函数的返回类型应为void数组类型以外的对象类型.

    C2011基本上会说同样的话.

  • 您不应该从函数返回指向(非静态)局部变量的指针,因为它在返回完成后不再在范围内(因此无效).

如果数组是静态分配的,或者通过malloc()等人动态分配数组,则可以返回指向数组开头的指针.

int *function1(void)
{
    static int a[2] = { -1, +1 };
    return a;
}

static int b[2] = { -1, +1 };

int *function2(void)
{
    return b;
}

/* The caller must free the pointer returned by function3() */
int *function3(void)
{
    int *c = malloc(2 * sizeof(*c));
    c[0] = -1;
    c[1] = +1;
    return c;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您有冒险精神,可以返回指向数组的指针:

/* The caller must free the pointer returned by function4() */
int (*function4(void))[2]
{
    int (*d)[2] = malloc(sizeof(*d));
    (*d)[0] = -1;
    (*d)[1] = +1;
    return d;
}
Run Code Online (Sandbox Code Playgroud)

小心那个功能声明!完全改变其含义并没有太大的改变:

int (*function4(void))[2]; // Function returning pointer to array of two int
int (*function5[2])(void); // Array of two pointers to functions returning int
int (*function6(void)[2]); // Illegal: function returning array of two pointers to int
int  *function7(void)[2];  // Illegal: function returning array of two pointers to int
Run Code Online (Sandbox Code Playgroud)