Jump to content

mapping between union and malloc memory

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
dhiru

dhiru

    Newbie

  • Members
  • Pip
  • 1 posts
(i m a student
our placements are going on
last week HP visited our campus
in the technical round they asked me this question)


union a{
some data;
};

mem=malloc(80);
and there is some data copied to the mem variable
now how one can map the mem to a

#2
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
something like this should work i guess:
union a *new = NULL;

mem=malloc(80);

if(mem != NULL)
{
     new = (union a*)(&mem);
}


#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,713 posts
That's not correct, since mem would have to be a pointer. That would assign the data beginning with mem somewhere in memory to the pointer. And you can't use new as a variable in C++, so I wouldn't use that either.

typedef union {
    /*some stuff*/
}A;

void *mem = malloc(/*arbitrary size*/);
A *myunion = (A *)mem;


#4
solartic

solartic

    Learning Programmer

  • Members
  • PipPipPip
  • 95 posts
ahh yeah indeed mem would have to be a pointer
well about the new i assumed c but yeah its better to avoid it