Is this C structure assignment statement legal? -


here code example followed 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 thinking since structure 'localstruct' created inside function (not using malloc) had local scope , memory locations stored free overridden once function stopped executing. however, tried running sample program , executed no issues. thinking second print statement going print gibberish screen since assigned 'mystruct' local variable 'localstruct' (versus 'localstruct' being dynamically allocated). know if 'localstruct' had been created using malloc there no such issues.

my question: assigning structure variable 'mystruct' (a non dynamic local variable) y use of pointer in function test okay , safe do? hope question clear.

assignment copies.

if did *x = &y (assuming types matched - if parameter declared st** x, example), copying address of y, since y go out of scope soon, assignment unsafe, feared.

but since you're doing *x = y instead (where parameter declared st* x), copying content of y *x, after y goes out of scope, data stored in *x should valid.


Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -