簡體   English   中英

函數返回指向 int 指針數組 5 的指針

[英]Function returning pointer to array 5 of pointer to int

我讀到這個問題: int *(*(x[3])())[5]; 行是什么? 在 C 中做什么?

其中有代碼行:

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

在這個答案https://stackoverflow.com/a/37364752/4386427

根據http://cdecl.org/這意味着

將 x 聲明為函數指針數組 3 返回指向 int 指針數組 5 的指針

現在我想知道這部分:

函數返回指向 int 指針數組 5 的指針

返回指向 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

如果是,原型看起來如何?

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

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

整數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_intarray[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM