检查一下错误
struct complex * sum (struct complex z, int N){ struct complex z_sum;
int i;
for (i=0; i<N; i++)
{
z_sum.re += z.re;
z_sum.im += z.im;
}
return &z_sum;
}
struct complex z_sum没初始化 struct complex z_sum;定义在了struct complex * sum (struct complex z, int N);函数体的内部,z_sum的作用域离开函数体后就会失效,也就是返回地址给指针,指针指向的数据不再可靠。
建议你将struct complex z_sum;定义在函数体之外。
根据你的函数定义,建议修改如下:#include "stdio.h"
struct complex
{
int re;
int im;
};
struct complex z_sum;
struct complex * sum (struct complex z[], int N)
{
int i;
for (i=0; i<N; i++)
{
z_sum.re += z.re;
z_sum.im += z.im;
}
return &z_sum;
}
int main(int argc, char* argv[])
{
struct complex z;
z.re=0;
z.im=0;
z.re=1;
z.im=1;
z.re=2;
z.im=2;
z.re=3;
z.im=3;
z.re=4;
z.im=4;
z.re=5;
z.im=5;
printf("%d\n",sum(z,6)->im);
return 0;
}
页:
[1]