函数返回指向int的指针数组5的指针

时间:2016-05-21 16:13:34

标签: c arrays function

我读到了这个问题:what does the line int *(*(x[3])())[5]; do in C?

有代码行:

int *(*(*x[3])())[5];

在这个答案中https://stackoverflow.com/a/37364752/4386427

根据http://cdecl.org/,这意味着

  

将x声明为指向函数的指针的数组3,返回指向int

的指针数组5的指针

现在我想知道这一部分:

  

函数返回指向int

的指针数组5的指针

函数的proto-type如何返回指向int的指针数组5的指针?

我试过了:

int* g()[5]    <---- ERROR: 'g' declared as function returning an array
{
    int** t = NULL;
    // t = malloc-stuff
    return t;
}

无法编译。

然后我试了

#include <stdio.h>
#include <stdlib.h>

int *(*(*x[3])())[5];

int** g()
{
    int** t = NULL;
    // t = malloc-stuff
    return t;
}

int main(void) {
    x[0] = g;
    return 0;
}

编译得很好但现在返回类型更像pointer to pointer to int。没有任何内容可以说pointer to array 5 of pointer to int

所以我的问题是:

是否可以编写一个返回pointer to array 5 of pointer to int的函数?

如果是的话,proto-type看起来怎么样?

如果不是,5声明中x的目的是什么?

int *(*(*x[3])())[5];
                  ^
                what does 5 mean here?

1 个答案:

答案 0 :(得分:1)

{strong>整数中的array[5]为:

int array[5]; /* read: array of 5 ints */

和指向该数组的指针(不仅指向数组的第一个元素,还指向整个数组5!)将是:

int(* ptr)[5] = &array; /* read: pointer to an array of 5 ints */

并且返回此类指针的函数将是:

int(* g())[5]; /*read: a function returning a pointer to an array of 5 ints */

按照相同的逻辑 pointers_to_int 中的array[5]为:

int* array_of_ptrs[5]; /* read: array of 5 pointers_to_int */

,指向该数组的指针将是:

int* (* PTR)[5] = &array_of_ptrs; /* read: pointer to an array of 5 pointers_to_int */

然后返回这样的指针的函数将是:

int* (* g())[5] /* read: function returning a pointer to an array of 5 pointers_to_int*/
/* just like @EOF said in the comments above! */

让我们尝试一下:

#include <stdio.h>

int array[5] ={1, 2, 3, 4, 5};

int a = 6, b = 7, c = 8, d = 9, e = 10;
int* array_of_ptrs[5] = {&a, &b, &c, &d, &e};

int(* g())[5] 
{
    return &array;
}

int* (* gg())[5]
{
    return &array_of_ptrs; 
}

int main()
{
int(* ptr)[5]; 
ptr = g();

int* (* PTR)[5];     
PTR = gg();
    
printf
("the value of the dereferenced 1st element of array_of_ptrs is: %d", *(*PTR)[0]);  

return 0;
}

clang prog.c -Wall -Wextra -std = gnu89输出:

array_of_ptrs的已取消引用的第一个元素的值是:6