在 c: 预期标识符或参数之前返回结构的函数中的错误



我是c的新手,我正在尝试创建一个函数,该函数接受两个double类型的参数作为输入,并返回一个包含每个参数的结构体作为成员,称为"real"和想象的。我得到的错误是:

error: expected identifier or ‘(’ before ‘double’

错误指向我定义函数的那行。我知道还有其他职位覆盖相同的错误,但是据我所知,这不是同样的问题在这些(以及道歉如果)。

下面是我的代码:
#include <stdio.h>
int main(void) {
return 0;
}
struct make_complex(double real_input, double imaginary_input) {
struct complex {
double real;
double imaginary;
} complex_output = {real_input, imaginary_input};
return complex_output; 
}

我最终想在main中调用make_complex函数,但我已经完全简化了main,以消除任何其他错误来源。我已经尝试在函数定义之前声明make_complex函数,如下所示:

struct make_complex(double real_input, double imaginary_input);

这不起作用。想法吗?

感谢您的宝贵时间。

函数的返回类型需要包括结构类型,而不仅仅是struct。并且应该在函数外部定义结构类型,以便可以在调用者中引用它。

#include <stdio.h>
struct complex {
double real;
double imaginary;
};
int main(void) {
return 0;
}
struct complex make_complex(double real_input, double imaginary_input) {
struct complex complex_output = {real_input, imaginary_input};
return complex_output; 
}

在这个函数声明中

struct make_complex(double real_input, double imaginary_input) {

编译器认为这一行声明了一个名为make_complex的结构体。

需要在函数声明之前定义complex结构,例如

struct complex {
double real;
double imaginary;
};
struct complex make_complex(double real_input, double imaginary_input) {
struct complex complex_output = {real_input, imaginary_input};
return complex_output; 
}

在C中,你甚至可以在函数返回类型

的声明中定义结构
struct complex { double real; double imaginary; }
make_complex(double real_input, double imaginary_input) {
struct complex complex_output = {real_input, imaginary_input};
return complex_output; 
}

虽然这不是个好主意。

最新更新