C语言编写返回struct的函数报错expected identifier or '(' before 'double'
问题原因
- 语法错误:C语言中返回结构体的函数定义语法为
[结构体类型] [函数名](参数列表),你当前的写法struct make_complex(...)将函数名误放在了struct关键字后,编译器会把make_complex识别为结构体标签,导致返回类型不完整,触发你遇到的编译报错。 - 作用域问题:你将
struct complex定义在make_complex函数内部,该结构体的作用域仅局限于函数内部,后续在main函数中无法定义对应类型的变量接收函数返回值,属于隐藏逻辑错误。
修复方案
- 先将
struct complex的定义移到所有函数之前,保证全局可访问该类型 - 修改
make_complex函数的返回值类型为完整的struct complex - 函数前置声明也要同步修改返回值类型
修复后的完整可运行代码如下:
#include <stdio.h> // 结构体定义放在全局位置,所有函数都可访问 struct complex { double real; double imaginary; }; // 可选的函数前置声明,若函数定义在调用位置之前可以省略 struct complex make_complex(double real_input, double imaginary_input); int main(void) { // 调用示例 struct complex test_num = make_complex(1.5, 2.5); printf("实部:%lf,虚部:%lf\n", test_num.real, test_num.imaginary); return 0; } // 函数返回类型明确为struct complex struct complex make_complex(double real_input, double imaginary_input) { struct complex complex_output = {real_input, imaginary_input}; return complex_output; }
内容的提问来源于stack exchange,提问作者lcleary
相关产品推荐
相关产品推荐

