c++ - 从指向函数指针数组的指针中存储返回值如何工作?
问题描述
此示例 (7.19) 摘自 Stephen Prata 的 C++ Primer 第 6 版。
#include <iostream>
// various notations, same signatures
const double * f1(const double ar[], int n);
const double * f2(const double[], int);
const double * f3(const double *, int);
int main()
{
using namespace std;
double av[3] = { 1112.3, 1542.6, 2227.9 };
// pointer to function
const double *(*p1)(const double *, int) = f1;
auto p2 = f2; // C++11 automatic type deduction
// pre-C++11 can use the following code instead
// const double *(*p2) (const double *, int ) = f2;
cout << "Using pointers to functions:\n";
cout << " Address Value\n";
cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;
cout << p2(av, 3) << ": " << *p2(av, 3) << endl;
// pa an array of pointers
// auto doesn't work with list initialization
const double *(*pa[3])(const double *, int) = { f1, f2, f3 };
// but it does work for initializing to a single value
// pb a pointer to first element of pa
auto pb = pa;
// pre-C++11 can use the following code instead
// const double *(**pb) (const double *, int) = pa;
cout << "\nUsing an array of pointers to functions:\n";
cout << " Address Value\n";
for (int i = 0; i < 3; i++)
cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;
cout << "\nUsing a pointer to a pointer to a function:\n";
cout << " Address Value\n";
for (int i = 0; i < 3; i++)
cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;
// what about a pointer to an array of function pointers
cout << "\nUsing pointers to an array of pointers:\n";
cout << " Address Value\n";
// easy way to declare pc
auto pc = &pa;
// pre-C++11 can use the following code instead
// const double *(*(*pc)[3])(const double *, int) = &pa;
cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;
// hard way to declare pd
const double *(*(*pd)[3]) (const double *, int) = &pa;
// store return value in pb
const double * pdb = (*pd[1]) (av, 3);
cout << pdb << ": " << *pdb << endl;
// alternative notation
cout << (*(*pd)[2])(av, 3) << ": " << *(*(*pd[2]))(av, 3) << endl;
// cin.get();
return 0;
}
// some rather dull functions
const double * f1(const double * ar, int n)
{
return ar;
}
const double * f2(const double * ar, int n)
{
return ar + 1;
}
const double * f3(const double * ar, int n)
{
return ar + 2;
}
指针*pdb发生了什么?指针是占用整个数组还是仅占用一个元素?当程序运行时,会在声明*pdb的地方引发异常。谁能告诉我里面发生了什么?
解决方案
pdb
就像其他指针一样。它由函数调用返回到f2
.
因为它只是一个指针,所以它指向一个元素。取决于您调用的函数及其合约,是否知道后面是否还有元素。
推荐阅读
- tensorflow - 如何组合具有不同时间步长的两个时间序列数据集?
- python - 用另一个数组中的值替换 numpy 数组中的所有 -1
- node.js - 您在哪里以及如何导入节点模块?
- ios - Swift - UIButton 以编程方式设置约束
- ssl - 使用 *.herokuapp.com 域的缺点?
- java - 是否有可能有 3 个相互更改的 EditText 可以在所有 3 个之间互换的 EditText?
- ubuntu - 如何在 Ubuntu 上为 2 个不同的视频驱动程序设置 2 个启动配置?
- javascript - 西班牙语使用者的日期格式 - 返回 NaN 或无效日期
- mysql - 为什么我不能将数据导入 MySQL 中的模式?
- java - Spring MVC 应用程序,如何使用依赖 jar 文件中的 jsp 视图配置 servlet