If it's a struct
then it can be done
*p = {var1, var2..};
But seems this doesn't work with union
:
union Ptrlist
{
Ptrlist *next;
State *s;
};
Ptrlist *l;
l = allocate_space();
*l = {NULL};
Only to get:
expected expression before ‘{’ token
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.
C allows you to initialize a union in two ways: Initialize a union by initializing the first member of a union. Or initialize a union by assigning it to another union with the same type.
A union can have member functions (including constructors and destructors), but not virtual functions.
In C99, you can use a designated union initializer:
union {
char birthday[9];
int age;
float weight;
} people = { .age = 14 };
In C++, unions can have constructors.
In C89, you have to do it explicitly.
typedef union {
int x;
float y;
void *z;
} thing_t;
thing_t foo;
foo.x = 2;
By the way, are you aware that in C unions, all the members share the same memory space?
int main ()
{
thing_t foo;
printf("x: %p y: %p z: %p\n",
&foo.x, &foo.y, &foo.z );
return 0;
}
output:
x: 0xbfbefebc y: 0xbfbefebc z: 0xbfbefebc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With