I'm practicing c and I want to return data of a struct to access it within an other location.
Let's say I have something like this:
typedef struct
{
int8 x;
u64 y;
u32 z;
} myData_t;
myData_t myData_g;
/*Setter*/
void WritemyData(const myData_t* data)
{
myData_g = *data;
}
How can I return the data which are stored within a global variable to be read within an other location. Can I not just do something like:
/*Getter*/
myData_t GettmyData(void)
{
return myData_g;
}
Would be thankful for any information!
CodePudding user response:
First of all, for things like this consider making the "global" a private variable instead, by adding static myData_t myData_g;
. Now nobody outside this .c file can access it intentionally/by accident.
As for your function GettmyData
, it will work fine. However, passing/returning structs by value is considered bad practice since it involves making a full copy of the struct on the stack, which may be slow and take up unnecessary memory temporarily.
This might be better idea might be:
void get_my_data (myData_t* obj)
{
*obj = myData_g;
}
Here you have to document that the caller should allocate the variable pointed at by obj
on the caller side.