You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言编写返回struct的函数报错expected identifier or '(' before 'double'

问题原因
  • 语法错误:C语言中返回结构体的函数定义语法为 [结构体类型] [函数名](参数列表),你当前的写法struct make_complex(...)将函数名误放在了struct关键字后,编译器会把make_complex识别为结构体标签,导致返回类型不完整,触发你遇到的编译报错。
  • 作用域问题:你将struct complex定义在make_complex函数内部,该结构体的作用域仅局限于函数内部,后续在main函数中无法定义对应类型的变量接收函数返回值,属于隐藏逻辑错误。
修复方案
  1. 先将struct complex的定义移到所有函数之前,保证全局可访问该类型
  2. 修改make_complex函数的返回值类型为完整的struct complex
  3. 函数前置声明也要同步修改返回值类型

修复后的完整可运行代码如下:

#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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:06:03