C代码编译错误:用int(void)类型表达式初始化int时指针整数转换不兼容
问题分析与解决方案
错误原因
在代码行 int cents = get_cents; 中,你直接使用函数名 get_cents 却未添加调用所需的括号 ()。在C语言里,单独的函数名代表该函数的地址指针,类型为 int (void),而你试图将这个指针赋值给 int 类型变量,这就引发了类型不兼容的编译错误——整数与函数指针无法直接转换。
解决方案
要调用函数并获取其返回值,必须在函数名后添加括号 ()(即使函数无参数)。修改该行代码为:
int cents = get_cents();
修正后的完整代码
#include <cs50.h> #include <stdio.h> int get_cents(void); int calculate_quarters(int cents); int main(void) { // Ask how many cents the customer is owed int cents = get_cents(); // Calculate the number of quarters to give the customer int quarters = calculate_quarters(cents); cents = cents - quarters * 25; } int get_cents(void) { int cents; do { cents = get_int("Change owed: "); // 注:原代码中"Changed"应为"Change" } while (cents < 0); return cents; } int calculate_quarters(int cents) { return 0; }
(注:顺便修正了原代码中字符串拼写错误"Changed"为"Change",不影响编译但更符合语义)
内容的提问来源于stack exchange,提问作者Abdul Khan
相关产品推荐
相关产品推荐

