Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中的函数指针、数组和左值_C_Arrays_Pointers - Fatal编程技术网

C语言中的函数指针、数组和左值

C语言中的函数指针、数组和左值,c,arrays,pointers,C,Arrays,Pointers,假设我们有以下函数(在C中): 所以我们知道,我们可以通过以下方式声明函数指针数组: int (*test[2]) (int a, int b); test[0] = sum; test[1] = diff; 但以下内容也是有效的(但我们使用堆分配): 到目前为止还不错。现在让我们记住,要声明一个由两个整数组成的(动态分配的)数组,我们可以执行以下操作: int* test = malloc( 2*sizeof(int)); 那么为什么我们不能将函数指针数组声明为 int (*test)

假设我们有以下函数(在C中):

所以我们知道,我们可以通过以下方式声明函数指针数组:

int (*test[2]) (int a, int b);
test[0] = sum;
test[1] = diff;
但以下内容也是有效的(但我们使用堆分配):

到目前为止还不错。现在让我们记住,要声明一个由两个整数组成的(动态分配的)数组,我们可以执行以下操作:

 int* test  = malloc( 2*sizeof(int));
那么为什么我们不能将函数指针数组声明为

int (*test) (int a, int b) = malloc( 2*sizeof(*test)); ?
int (*test) (int a, int b) = malloc( 2*sizeof(*test));
是因为测试与
*test
**test
(等等)相同,
malloc(2*sizeof(*test))
返回指向函数指针的指针,因此无法将其分配给
(*test)

如果这个假设是正确的,你能详细解释一下为什么会出现编译错误吗

error: lvalue required as left operand of assignment
当我们试着去做

int (*test) (int a, int b) = malloc( 2*sizeof(*test));
test=diff; //<--- This is ok.
test+1 = sum; //<--- This is what gives the error!
 int (*test) (int a, int b) = malloc( 2*sizeof(*test));
 test=diff; //<--- This is ok.
 test+1 = sum; //<--- This is what gives the error!
那么为什么我们不能将函数指针数组声明为

int (*test) (int a, int b) = malloc( 2*sizeof(*test)); ?
int (*test) (int a, int b) = malloc( 2*sizeof(*test));
因为
test
不指向函数指针;它是一个函数指针。因此,它不能指向函数指针数组的第一个元素

如果需要函数指针数组,请使用上一种形式:

这里,
*test
具有函数指针类型,因此
test
可以(并且确实)指向函数指针数组的第一个元素。进一步:

当我们试着去做

int (*test) (int a, int b) = malloc( 2*sizeof(*test));
test=diff; //<--- This is ok.
test+1 = sum; //<--- This is what gives the error!
 int (*test) (int a, int b) = malloc( 2*sizeof(*test));
 test=diff; //<--- This is ok.
 test+1 = sum; //<--- This is what gives the error!
int(*测试)(int a,int b)=malloc(2*sizeof(*测试));

测试=差异//因为不能在C中对函数进行位复制,所以无法获得两个函数的连续数组,这就是为什么
int(*)(
不能是数组的原因
test+1
无效,可能是因为函数没有固定的大小,所以它不知道指针要增加多少字节。
int(*test)(int a,int b)=malloc(2*sizeof(*test))
也不正确。@这是的,我知道,但因为它不会让编译器生气,我想知道编译器时发生了什么。抱歉,如果问题是基本的,但这种事情让我夜惊你的函数也不正确,它们应该返回值。是的,对不起。我将对其进行编辑,问题是当你声明一个函数时,函数名本身就是一个函数指针,因此我假设没有办法连接指向int-case数组的指针。但我想更多地了解这两种情况之间的区别。顺便说一句,谢谢你的回答。:)我在主问题中添加了一个小的子问题作为编辑。非常感谢。说名称“是”指针是错误的。不是。在大多数上下文中,它只是“衰减”到一个指针,就像数组名一样。但是,当它是
&
sizeof
运算符的操作数时,不会发生这种情况。
error: lvalue required as left operand of assignment
 int (*test) (int a, int b) = malloc( 2*sizeof(*test));
 test=diff; //<--- This is ok.
 test+1 = sum; //<--- This is what gives the error!