简体   繁体   English

为什么我的 function 没有修改 C 结构中变量的值?

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

This is my input.这是我的输入。 I must write a function, which give me minus Zesp.Im我必须写一个 function,它给我减去 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?我不知道为什么我得到 3.321 而不是 -3.321?

I edit my program, my teacher said that I can't modify argument of a function spZ.我编辑我的程序,我的老师说我不能修改 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;
}

You're passing a copy of the structure to the function.您将结构的副本传递给 function。 It returns a copy, but you're not using the result.它返回一个副本,但您没有使用结果。

You need to assign the result of the function to the variable.您需要将 function 的结果分配给变量。

z1 = spZ(z1);

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.在您的代码中,此 function 返回应该反转此数字的新实例。 So, you should save the result of this function call:所以,你应该保存这个 function 调用的结果:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM