C: union members get spoiled when compiled
Here's C code that prints 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 no problem, but it showed a slightly different result, printing out a strange value for the name instead of showing the correct one.
Name: \257
Age: 175
Height: 175
Any good solutions would be much appreciated. Thank!
source to share
I think you might confuse the structure with union. In a union, an item shares memory.
This means that when you write to the field of age
your union, you are at the same time overwriting the content height
and name
, which you do not intend to do. The same thing happens when you write to height
where you write the latest. You can notice this pretty well, because at the end age
it is the same value as height
and the first character name
is actually character number 175 (displayed as escaped octal \257
).
Try using struct
instead union
.
source to share