Why does my function not modify the value of variable in a struct in C?

痴心易碎 提交于 2021-02-13 17:41:36

问题


This is my input. I must write a function, which give me minus Zesp.Im

struct Zesp { double Re; 
                    double Im; 
                };
struct Zesp z1 = { .Re = 5.323 ,.Im= 3.321};
typedef struct Zesp zesp;

zesp spZ(zesp z)
{
    z.Im = -(z.Im);
    
    return z;
}

int main ()
{
    spZ(z1);
    printf("%.2f, %.2f\n", z1.Re, z1.Im);
    return 0;
}

I don't know why I get 3.321 instead of -3.321?

I edit my program, my teacher said that I can't modify argument of a function spZ.

I get a segmentation fault


#include <stdio.h>

struct Zesp { double Re; 
                    double Im; 
                };
struct Zesp z1 = { .Re = 5.323 ,.Im= 3.321};
typedef struct Zesp zesp;

zesp spZ(zesp z)
{
    z.Im = -(z.Im);
    z = spZ(z);

    return z;
}

int main ()
{
    spZ(z1);
    printf("%.2f, %.2f\n", z1.Re, z1.Im);
    return 0;
}

回答1:


You're passing a copy of the structure to the function. It returns a copy, but you're not using the result.

You need to assign the result of the function to the variable.

z1 = spZ(z1);



回答2:


The problem is that the copy of this struct is being modified. In your code, this function returns the new instance of zest that should have this number inverted. So, you should save the result of this function call:

z1 = spZ(z1);

Or you can modify the argument itself, then you should pass it by pointer:

void spZ(zesp* z)
{
    z->Im = -(z->Im);
}


来源:https://stackoverflow.com/questions/61726751/why-does-my-function-not-modify-the-value-of-variable-in-a-struct-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!