C语言结构体多函数传参及递归程序调试 &符号前语法错误求解
问题根因
你遇到的error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token报错属于C/C语法差异类错误:C语言原生不支持引用(&)传参语法,该特性为C独有,使用C编译器编译带C++引用写法的代码就会触发该类报错,你代码中共有3处使用了引用传参的写法,对应你提到的3个同源错误。
需要修改的内容
- 调整
scan_complex、print_complex、multiply_complex三个函数的形参定义:将struct complex &a改为指针形式struct complex *a,函数内部访问结构体成员的.运算符替换为-> - 调整上述三个函数的调用逻辑:传参时传入结构体地址(前缀加
&),如果原参数是结构体指针则直接传递不需要解引用
修复后可正常编译运行的完整代码
#include <stdio.h> #include <stdlib.h> #include <math.h> struct complex { int real; int img; }; void scan_complex(struct complex *a) { printf("Enter a and b where a + ib is the complex number."); printf("\na = "); scanf("%d", &a->real); printf("b = "); scanf("%d", &a->img); } void print_complex(struct complex *a) { printf(" %d + %di", a->real, a->img); } struct complex * add_complex(struct complex *a,struct complex *b) { struct complex *c = (struct complex *)malloc(sizeof(struct complex)); c->real = a->real + b->real; c->img = a->img + b->img; return c; } void multiply_complex(struct complex *a, struct complex *b) { struct complex c; c.real = a->real*b->real - a->img*b->img; c.img = a->img*b->real + a->real*b->img; if (c.img >= 0) { printf("Multiplication of the complex numbers = %d + %di", c.real, c.img); } else { printf("Multiplication of the complex numbers = %d %di", c.real, c.img); } } struct complex* f(int n, struct complex *c) { if(n==0) return c; return add_complex(c,f(n-1,c)); } float abs_complex(struct complex c) { return sqrt(c.real*c.real + c.img *c.img); } int main() { struct complex a; struct complex b; scan_complex(&a); scan_complex(&b); printf("absolute of : "); print_complex(&a); printf(" %f\n",abs_complex(a)); printf("\n"); print_complex(&a); printf(" + "); print_complex(&b); printf(" = "); struct complex *c =add_complex(&a,&b); print_complex(c); printf("\n"); multiply_complex(&a,&b); printf("\n"); struct complex *d = f(3,&a); print_complex(d); printf("\n"); // 补充:可自行添加free释放malloc申请的内存避免泄漏 free(c); // 注意f函数递归申请的多层内存需要额外逻辑释放,此处仅做示例 return 0; }
补充说明
如果你不想修改为指针传参,也可以将代码后缀改为.cpp使用C++编译器编译,也可以解决当前报错。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

