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