Re: Struct assignment
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Sat, 30 Jun 2007 18:12:48 +0100
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
.
- Follow-Ups:
- Re: Struct assignment
- From: Keith Thompson
- Re: Struct assignment
- From: Serve Lau
- Re: Struct assignment
- References:
- Struct assignment
- From: Grey Alien
- Struct assignment
- Prev by Date: Re: Machine epsilon: conclusion
- Next by Date: Re: Struct assignment
- Previous by thread: Re: Struct assignment
- Next by thread: Re: Struct assignment
- Index(es):
Relevant Pages
|