鱼C论坛

 找回密码
 立即注册
查看: 1389|回复: 2

[已解决]检查一下错误

[复制链接]
发表于 2019-1-9 20:38:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
struct complex * sum (struct complex z[10], int N)
{ struct complex z_sum;
    int i;

for (i=0; i<N; i++)
{
    z_sum.re += z[i].re;
    z_sum.im += z[i].im;
}

     return &z_sum;
}
最佳答案
2019-1-19 09:55:59
struct complex z_sum;定义在了struct complex * sum (struct complex z[10], 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[i].re;
    z_sum.im += z[i].im;
}

return &z_sum;
}


int main(int argc, char* argv[])
{
        struct complex z[6];
        z[0].re=0;
        z[0].im=0;
        z[1].re=1;
        z[1].im=1;
        z[2].re=2;
        z[2].im=2;
        z[3].re=3;
        z[3].im=3;
        z[4].re=4;
        z[4].im=4;
        z[5].re=5;
        z[5].im=5;

        printf("%d\n",sum(z,6)->im);
        return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-1-14 22:34:32 | 显示全部楼层
struct complex z_sum没初始化
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-1-19 09:55:59 | 显示全部楼层    本楼为最佳答案   
struct complex z_sum;定义在了struct complex * sum (struct complex z[10], 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[i].re;
    z_sum.im += z[i].im;
}

return &z_sum;
}


int main(int argc, char* argv[])
{
        struct complex z[6];
        z[0].re=0;
        z[0].im=0;
        z[1].re=1;
        z[1].im=1;
        z[2].re=2;
        z[2].im=2;
        z[3].re=3;
        z[3].im=3;
        z[4].re=4;
        z[4].im=4;
        z[5].re=5;
        z[5].im=5;

        printf("%d\n",sum(z,6)->im);
        return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-3 06:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表