📜  声明一个C / C++函数返回指向整数指针数组的指针

📅  最后修改于: 2021-05-30 11:34:00             🧑  作者: Mango

声明“一个带有int *参数的函数,该函数返回指向4个整数指针的数组的指针”。

乍一看,它看起来很复杂,我们可以使用一系列分解后的语句来声明所需的函数。

1.我们需要一个带有参数int *的函数,

function(int *)

2.一个带有参数int *的函数,返回指向的指针

(*function(int *))

3.具有参数int *的函数,返回指向4数组的指针

(*function(int *))[4]

4.一个带有参数int *的函数,返回指向4个整数指针数组的指针

int *(*function(int *))[4];

我们如何确保以上声明正确无误?以下程序可以交叉检查我们的声明,

#include
  
// Symbolic size
#define SIZE_OF_ARRAY (4)
  
// pointer to array of (SIZE_OF_ARRAY) integers
typedef int *(*p_array_t)[SIZE_OF_ARRAY];
  
// Declaration : compiler should throw error
// if not matched with definition
int *(*function(int *arg))[4];
  
// Definition  : 'function' returning pointer to an
// array of integer pointers
p_array_t function(int *arg)
{
   // array of integer pointers
   static int *arr[SIZE_OF_ARRAY] = {NULL};
  
   // return this
   p_array_t pRet = &arr;
  
   return pRet;
}
  
int main()
{          
}

宏SIZE_OF_ARRAY用于数组大小的符号表示。 p_array_t类型定义为“指向4个整数的数组的指针”。如果我们的声明是错误的,则程序将在’ 函数 ‘定义上引发错误。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”