PDA

View Full Version : unions and pointers


sans-hubris
07-25-2002, 06:00 AM
I was trying to do some funky coding with unions just for fun when I found out that if you have a pointer in the union and you try to assign a pointer to an instance of the union, the compiler errs out (in particular, I'm using gcc 2.95.3, fyi.)

E.g.:

union {
int * x;
int y;
}z;
z = (int)malloc(5*sizeof(int));
/* This does not seem to be legal. */


Is there a way around this?

l01yuk
07-25-2002, 09:10 AM
I haven't tried this but

union a { /* Give yourself the choice. */
int * x;
int y;
} *z; /* Make this a pointer. */

z = malloc(5*sizeof(*z));


Don't cast malloc, #include <stdlib.h> instead. :)

Strike
07-25-2002, 01:40 PM
Well, first of all, you are assigning an int to something that isn't an int. Secondly, why are you casting the result of malloc (a void *) to an int? And lastly, why are you malloc'ing space for int's and not for the union. l01yuk has the right idea, it seems to me.

PrBacterio
07-25-2002, 06:10 PM
umm wtf? Its not really clear what you're trying to do here, but what you posted showed a severe lack of understanding of how pointers, unions and C in general work.

But I think you meant to do

z.x = malloc(sizeof(int) * 5);

or something along those lines...

sans-hubris
07-25-2002, 10:58 PM
Strike was right, I made the cast incorrectly.

While l01yuk's code works, it defeats the purpose of what I was trying to do.

PrBacterio, I never use unions for normal coding (I find them dangerous.) As I said in my first post, this was just for something fun. I wasn't exactly sure how unions could work.

jemfinch
07-26-2002, 03:33 AM
Originally posted by sans-hubris
PrBacterio, I never use unions for normal coding (I find them dangerous.) As I said in my first post, this was just for something fun. I wasn't exactly sure how unions could work.

They're not dangerous, you just gotta tag'em.

Jeremy