Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulate structs in void functions

Tags:

c

struct

I'm not very firm in using structs and currently trying to pass a struct through a void function. The struct is defined in a shard header, as well as my void function:

/* "main.h" */

struct input{
    unsigned int NO;
    double RA;
    double DE;
    double MV;
};

void full_view_equ(struct input, struct input);

The function looks like this, it is nessecary to use two different structs. Struct EQU already contains values, OUTPUT will be uninitialized:

/* "transformations.c" */

#include "main.h"

void full_view_equ(struct input EQU, struct input OUTPUT){
    OUTPUT.NO = EQU.NO;
    OUTPUT.RA = -radian2degree(EQU.RA);
    OUTPUT.DE = radian2degree(EQU.DE);
    OUTPUT.MV = EQU.MV;
}

I'm calling the function with the two structs EQU and OUTPUT like this:

struct input EQU, OUTPUT;

full_view_equ(EQU, OUTPUT);

The problem is, that within the function, OUTPUT has the expected values. Outside the function, all entries of OUTPUT are zero instead.

I can't see what's wrong with it, before i was using arrays instead of structs and all was working fine.

like image 961
van Avatar asked Mar 15 '26 18:03

van


2 Answers

You must use a pointer to the structure and pass that to the function, in your code the OUTPUT struct in the function is actually a copy of the original one and changing the copy won't change the original one.
for declaring a pointer to a struct simply use this code:

struct input *OUTPUT;

and use this header for your function:

void full_view_equ(struct input EQU, struct *input OUTPUT)

and the call to the function would be:

full_view_equ(EQU, &OUTPUT);
like image 142
Amen Avatar answered Mar 17 '26 09:03

Amen


Function arguments are passed by value. So you need to use pointers to modify value outside the function:

void full_view_equ(struct input EQU, struct input *OUTPUT){
    OUTPUT->NO = EQU.NO;
    OUTPUT->RA = -radian2degree(EQU.RA);
    OUTPUT->DE = radian2degree(EQU.DE);
    OUTPUT->MV = EQU.MV;
}

and call it like

full_view_equ(EQU, &OUTPUT);
like image 29
Yu Hao Avatar answered Mar 17 '26 08:03

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!