Eric said:
Mark said:
On Mon, 06 Jun 2005 14:40:57 -0400, in comp.lang.c , Eric Sosman
How do i easily assign one struct to another of a different type?
struct Object object = allocate_object();
struct Widget widget = (struct Widget)object; /* doesn't work */
Why would you expect this to do anything sensible?
I imagine this arises from some sort of pseudo OO environment, [...]
As do I, hence the appeal for more information about the
context. It may turn out that `struct Object' is a "prefix"
of `struct Widget', or even an embedded element as in
struct Widget {
struct Object your_honor;
long time_no_see;
double trouble;
short shrift;
};
But the O.P. needs to supply more information before we (or I,
at any rate) can suggest how to proceed.
The above struct nesting is what i have.
I was hoping to do something like:
struct Widget widget = (struct Widget)allocate_object1();
No, you can't cast to a structure type in C.
Anyway what is allocate_object1() actually returning? Since C doesn't have
references it would make most sense for this to be a pointer. In which
case you would need to cast it to a pointer of the appropriate type. And
it had better be a struct Widget that allocate_object1() allocates, or
I guess you could get away with a "subtype" of that i.e. one with a
struct widget as its first member.
The other way of doing it is of course:
struct Widget widget;
allocate_object2((struct Object*)&widget);
Again, what type of object is allocate_object2() supposed to be
allocating? In fact in this case it isn't allocating anything, probably
just filling in fields, but for what? If is just a struct Object then the
rest of the fields in struct Widget are going to be left uninitialised.
There's the same problem in the first example. But if that isn't a problem
then this is a reasonable way to handle it in C.
You really need to explain what it is you are trying to achieve with
this operation.
allocate_object() deals only with stack memory (ie, no mallocs).
OK, I see why the first example is returning a structure rather than a
pointer then. Of course you could write
widget.your_honor = allocate_object1();
but I gues you want something with the feel of inheritance.
Lawrence