Junior
Junior

Reputation: 17

Using pointers and union

I've just started to learn C. I think I did something wrong with the pointer here or didn't understand the meaning of it. Look this:

#include <stdio.h>

union Uniao{
int i;
float f;
char c[4];
};
void test(union Uniao *uniao);
int main(){
union Uniao uniao;
printf("uniao.i: %x\n"
    "uniao.f: %x\n"
    "uniao.c: %x\n",
    &uniao.i, &uniao.f,&uniao.c);
test(&uniao);
}
void test(union Uniao *uniao){
printf("uniao.i: %x\n"
    "uniao.f: %x\n"
    "uniao.c: %x\n",
    uniao->i, uniao->f,uniao->c);
}

As I understood, a pointer points to the memory location of the original variable. So the output using the pointer should be the same of the output using the original variable. But my output is something like:

uniao.i: bfeac1dc
uniao.f: bfeac1dc
uniao.c: bfeac1dc
uniao.i: b77abff4
uniao.f: 80000000
uniao.c: beef57fe

Is there something wrong with my pointer or I misunderstood it?

Upvotes: 0

Views: 96

Answers (4)

gnasher729
gnasher729

Reputation: 52566

Turn warnings on on your compiler, so that it tells you what it thinks of your code. It should find about six or so bad bugs.

Upvotes: 0

DNT
DNT

Reputation: 2395

IN your first printf statement in main you use '&' that returns the address of each member (all should be same for a union), but in 'Test' function you pass the values of each union member anot the addresses - i.e. no '&'. This is why you get different output values.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596843

main() is formatting the memory addresses of the union members, whereas test() is formatting the values of the members instead.

Upvotes: 0

OSborn
OSborn

Reputation: 895

In the first case, you're printing the address of each member of the union. Being members of a union, they all have the same address. Inside of the function, you're printing the values of the members. (Which, having different types, will produce odd results here.) Adding & before each unaio in the second printf call will give you the results you expect.

Upvotes: 6

Related Questions