Here is a code example followed by my question:
#include <stdio.h>
#include <string.h>
struct st {
char stringField[100];
int intField;
};
typedef struct st st;
void test(st *parameterStruct)
{
st localStruct;
strcpy(localStruct.stringField, "HELLO");
localStruct.intField = 5;
*parameterStruct = localStruct;
}
int main()
{
st myStruct;
strcpy( myStruct.stringField, "XXX" );
myStruct.intField = 9;
printf("%s,%i\n", myStruct.stringField, myStruct.intField );
test(&myStruct);
printf("%s,%i\n", myStruct.stringField, myStruct.intField);
return 0;
}
OUTPUT:
XXX,9
HELLO,5
I was thinking that since the structure 'localStruct' was created inside a function (NOT using malloc) it had local scope and thus the memory locations where it was stored were free to be overridden once the function stopped executing. However, I tried running this sample program and it executed with no issues. I was thinking that the second print statement was going to print gibberish to the screen since I assigned 'myStruct' to local variable 'localStruct' (versus 'localStruct' being dynamically allocated). I know if 'localStruct' had been created using malloc there would be no such issues.
My question: is assigning the structure variable 'myStruct' (a non dynamic local variable) to y by the use of a pointer in the function test okay and safe to do? I hope that the question is clear.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).
If the structures are of compatible types, yes, you can, with something like: memcpy (dest_struct, source_struct, sizeof (*dest_struct)); The only thing you need to be aware of is that this is a shallow copy.
In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.
Assignment always copies.
If you did something like *x = &y
(assuming the types matched - if the parameter was declared as st** x
, for example), you would be copying the address of y
, but since y
will go out of scope soon, that assignment would be unsafe, as you feared.
But since you're doing *x = y
instead (where the parameter is declared st* x
), you are copying the content of y
to *x
, so even after y
goes out of scope, the data stored in *x
should be valid.
Yes. It's safe.
When you assign:
*x = y;
The members of y
are copied into the corresponding members of *x
. It works as if you did a member to member copy yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With