MarshallLee
MarshallLee

Reputation: 1330

C: union members become corrupted when compiled

Here's a C code that prints out the member information to the console.

#include "learnc0006.h"
#include "stdio.h"
#include "string.h"

union Member {
    char name[20];
    int age;
    int height;
};

void printMember(union Member data);

int learnc0006() {
    union Member data;

    strcpy(data.name, "Rico Angeloni");
    data.age = 30;
    data.height = 175;

    printMember(data);
    return 0;
}

void printMember(union Member data) {
    printf("Name: %s\n", data.name);
    printf("Age: %d\n", data.age);
    printf("Height: %d\n", data.height);
}

I expected that there would be no problem, but it showed a little bit different result, printing out a strange looking value for the name instead of showing the proper one.

Name: \257
Age: 175
Height: 175

Any good solutions will be very much appreciated. Thank you!

Upvotes: 3

Views: 404

Answers (1)

Jonas Schäfer
Jonas Schäfer

Reputation: 20718

I think you might be confusing struct with union. In a union, the element share the memory.

That means that when you write to the age field of your union, you are at the same time overwriting contents of height and name, which is not what you intend. The same holds when you write to height, where you write last. You can observe that pretty well, because in the end age is the same value as height and the first character of name is in fact the character number 175 (displayed as escaped octal \257).

Try to use struct instead of union.

Upvotes: 8

Related Questions