假设我们有以下函数(在C中):
int sum(int a, int b){
return a+b;
}
int diff(int a, int b){
return a-b;
}
Run Code Online (Sandbox Code Playgroud)
所以我们知道我们可以通过以下方式声明一个函数指针数组:
int (*test[2]) (int a, int b);
test[0] = sum;
test[1] = diff;
Run Code Online (Sandbox Code Playgroud)
但以下也有效(但我们使用堆分配):
int (**test) (int a, int b) = malloc( 2*sizeof(*test));
test[0] = sum;
test[1] = diff;
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.现在让我们记住,我们可以做一个(动态分配的)两个整数的数组:
int* test = malloc( 2*sizeof(int));
Run Code Online (Sandbox Code Playgroud)
那么为什么我们不能将一个函数指针数组声明为
int (*test) (int a, int b) = malloc( 2*sizeof(*test)); ?
Run Code Online (Sandbox Code Playgroud)
是因为测试与*test和**test(等等)相同,malloc( 2*sizeof(*test))是返回指向函数指针的指针,因此无法分配给它(*test)?
如果这个假设是正确的,你能详细解释为什么我们得到编译错误
error: lvalue required as left operand of assignment
Run Code Online (Sandbox Code Playgroud)
当我们尝试做的时候
int (*test) (int a, int b) = malloc( 2*sizeof(*test));
test=diff; //<--- This is ok.
test+1 = sum; //<--- This is what gives the error!
Run Code Online (Sandbox Code Playgroud)
免责声明:我认为这是一个基本问题,假设是正确的,但我希望有一个更好的解释,让这种事情一劳永逸.
编辑:
请注意,这相当于
int (*test) (int a, int b) = malloc( 2*sizeof(*test));
*test=*diff; //<--- This is ok.
*(test+1) = *sum; //<--- This is what gives the error!
Run Code Online (Sandbox Code Playgroud)
因为这与案件有点类似:
int *test = malloc(2*sizeof(*test));
*test = 0;
*(test+1) = 1;
Run Code Online (Sandbox Code Playgroud)
R..*_*R.. 11
那么为什么我们不能将一个函数指针数组声明为
Run Code Online (Sandbox Code Playgroud)int (*test) (int a, int b) = malloc( 2*sizeof(*test));
因为test不指向函数指针; 它是一个函数指针.因此,它不能指向函数指针数组的第一个元素.
如果你想要一个函数指针数组,请使用前一个表单:
Run Code Online (Sandbox Code Playgroud)int (**test) (int a, int b) = malloc( 2*sizeof(*test));
这里,*test有函数指针类型,因此test可以(并且确实)指向函数指针数组的第一个元素.进一步:
Run Code Online (Sandbox Code Playgroud)error: lvalue required as left operand of assignment当我们尝试做的时候
Run Code Online (Sandbox Code Playgroud)int (*test) (int a, int b) = malloc( 2*sizeof(*test)); test=diff; //<--- This is ok. test+1 = sum; //<--- This is what gives the error!
无论什么类型test,test+1=anything总是无效C. test+1永远不能是左值.我不明白为什么你会期望这个工作.
海湾合作委员会还在报道你的计划中的另一个错误sizeof(*test).由于*test有函数类型,sizeof(*test)是无效的,但是GCC默默地为它赋值1.这导致为函数指针分配的内存太少,但无论如何都没关系,因为在下面的行中你丢弃了你得到的内存malloc和分配别的东西test.
| 归档时间: |
|
| 查看次数: |
169 次 |
| 最近记录: |