gpt4 book ai didi

c - 将指针传递给不符合形式参数要求的函数

转载 作者:太空狗 更新时间:2023-10-29 15:01:29 25 4
gpt4 key购买 nike

int valid (int x, int y) {
return x + y;
}

int invalid (int x) {
return x;
}

int func (int *f (int, int), int x, int y) {
//f is a pointer to a function taking 2 ints and returning an int
return f(x, y);
}

int main () {
int val = func(valid, 1, 2),
inval = func(invalid, 1, 2); // <- 'invalid' does not match the contract

printf("Valid: %d\n", val);
printf("Invalid: %d\n", inval);

/* Output:
* Valid: 3
* Invalid: 1
*/
}

inval = func(invalid, 1, 2); 行,为什么我没有收到编译器错误?如果 func 需要一个指向采用 2 个 int 的函数的指针,而我将一个指针传递给一个采用单个 int 的函数,为什么编译器不报错?

此外,由于发生这种情况,invalid 函数中的第二个参数 y 会发生什么情况?

最佳答案

why isn't the compiler complaining?

也许您需要更好的编译器? gcc 在这段代码中说 warning: passing argument 1 of ‘func’ from incompatible pointer type

Also, since this is happening, what happens to the second parameter y in the invalid function?

可能发生的情况是,编译器执行它通常会执行的任何操作来传递参数(将其压入堆栈、将其放入指定的寄存器等)。但是,使用错误数量的参数调用函数是未定义的行为,因此无法保证 - 程序可能会崩溃,或者编译器可能会生成 monkeys fly out of your nose。 .

关于c - 将指针传递给不符合形式参数要求的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2764494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com