Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Question on Unions in C

Name: Anonymous 2012-06-24 2:12

So, I know that a pointer is a variable that stores a memory address (basic 4 or 8 bytes). If I place a pointer in a Union type, does the memory address stored by the pointer share the same memory space as the other types, or does the data at the memory address share the same memory?

Or, in other words, if I union a double and a char*, will I memory leak/segfault if I assign the double to anything?

Name: Anonymous 2012-06-24 16:22

>>12
There's nothing wrong with storing pointers together with other types in an union.

Syntax and code semantics are never wrong per se. Your program, on the other hand, might be wrong because it uses syntax/semantics against the intended goal.

For example, one might create a variant type in C using the following:

struct variant {
    enum type { type_integer, type_string } type;
    union {
        int integer;
        char *restrict string;
   } data;
};

struct variant variant_copy(struct variant variant) {
    struct variant new_variant;
    if (variant.type == type_string) {
        new_variant.data.string = malloc(strlen(variant.data.string) + 1);
        if (!new_variant.data.string)
            abort();
        strcpy(new_variant.data.string, variant.data.string);
    }
    else
        new_variant.data = variant.data;
    new_variant.type = variant.type;
    return new_variant;
}

void variant_free(struct variant variant) {
    if (variant.type == type_string)
        free(variant.data.string);
}

It's perfectly legitimate to employ pointers and other data types in a union type. Just make sure you're accessing the correct fields according to the language rules.

Unions are useful to create a degree of polymorphism in C.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List