struct T
{
...
};
struct T array[10];
struct T* p = &array[0];
struct T* q = &array[0];
*p = *q;
Self-Assignment in C
In C, is self-assignment of a struct gauranteed to give correct results? Here's a simply, non-realistic, example:
Yes, self-assignment is safe. If your structures overlap being equal, though, you might get some problems (but this situation does not arise in normal use).
Quote:Original post by ToohrVyk
... If your structures overlap being equal...
Sorry, I'm not following. What do you mean by this?
Quote:Original post by willisQuote:Original post by ToohrVyk
... If your structures overlap being equal...
Sorry, I'm not following. What do you mean by this?
Sorry, I meant: overlap without being equal. For example:
Quote:typedef struct Pair {
int a;
int b;
}
int arr[3];
Pair* p1 = (Pair*) arr;
Pair* p2 = (Pair*) (arr + 1);
*p1 = *p2;
In this situation, p1->b and p2->a are the same memory object: the structures overlap without being equal. As far as I know, the assignment operation above has undefined behaviour.
be aware: some things won't work, like if the structures partly overlap:
char datablock[1023];
struct sometype
{
long data[10];
};
void test (void)
{
// generate two overlapping pointers.
sometype * t1 = (sometype *) datablock+100;
sometype * t2 = (sometype *) datablock+90;
// and assign them:
*t2 = *t1;
// this does not guarantee that t2 will have the same content of t1, even if you expect t1 to be destroyed (partly overridden).
}
When you assign structures the compiler assumes they don't overlap in memory. Think memcpy instead of memmove.
This *can* something you want to consider, especially if you code pure C, where there are reasons to use suck nasty things.
char datablock[1023];
struct sometype
{
long data[10];
};
void test (void)
{
// generate two overlapping pointers.
sometype * t1 = (sometype *) datablock+100;
sometype * t2 = (sometype *) datablock+90;
// and assign them:
*t2 = *t1;
// this does not guarantee that t2 will have the same content of t1, even if you expect t1 to be destroyed (partly overridden).
}
When you assign structures the compiler assumes they don't overlap in memory. Think memcpy instead of memmove.
This *can* something you want to consider, especially if you code pure C, where there are reasons to use suck nasty things.
Quote:Original post by Anonymous Poster
be aware: some things won't work, like if the structures partly overlap:
Already been said.
Quote:
When you assign structures the compiler assumes they don't overlap in memory. Think memcpy instead of memmove.
Now that I think of it: how can memmove be implemented without an additional copy?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement