Re: Struct assignment



Grey Alien wrote, On 30/06/07 17:43:
If I have the ff struct:

struct A
{
unsigned int i;
char s[LONG_ENOUGH];
} a, b;


And use them in code like this:

a.i = 42 ;
strcpy(a.s,"test");

b.i = 100 ;

b = a ;

at this point, a (bitwise?) copy of a is made to b.

It is not a bitwise copy, it is a copy of all the elements in the struct.

> Question is:

1). is b.s now ptr to a.s ? (I think so)

Since b.s was not defined as a pointer, what makes you think an assignment could magically transform it from being an array in to being a pointer? You need to read section 6 of the comp.lang.c FAQ at http://c-faq.com/ specifically the questions dealing with whether pointers and arrays are the same thing.

If so, what happens if for instance variable 'a' goes out of scope (?)

2). Does the compiler generate an implicit "memcpy" or "memmove" behind the scenes when it sees an assignment like this (to avoid dangling ptrs)?

It is very rare for C to do things behind your back. Had there been pointers in your struct (which there were not) then after the assignment they would point to the same place as they point in the original struct, and when that place is no longer valid (an automatic that goes out of scope, for example) the pointers are no longer valid.
--
Flash Gordon
.



Relevant Pages

  • Re: problem with macros
    ... x,y,z doubles, and the pointers are set up to point to each of the x,y,z ... or copied by assignment to another struct: ... copy" technique rather than simple assignment. ...
    (comp.lang.c)
  • Re: struct assignment in C
    ... assignment between C structs always result in the copying of the ... struct one; ... However if B includes pointers to data elsewhere, ...
    (comp.lang.c)
  • Re: why cannot assign to function call
    ... as in Python, Java, REALbasic, .NET, etc. ... Pointers are passed and assigned by value, ... If you simply use the name, you get by-value semantics. ... Python's assignment semantics, and further appear ...
    (comp.lang.python)
  • Re: Simple question, err... I think
    ... Your nodes contain no other indication of which pointers are valid, ... struct CountedObject ... int is_red; ... bool lament(char const s) ...
    (comp.programming)
  • Re: porting problems encountered
    ... Tru64 compiles long variables to size 8 bytes while VMS and HP-UX ... platform, the size of the structure would be 12 bytes. ... when it got to the AS/400 with 128 bit pointers. ... Using the struct from before: ...
    (comp.os.vms)