12

I'm doing a class in c++ that supports any kind of variable to help me in a future project. The thing is, when I try to assign a value to a void* variable, I get the error: void* is not a pointer-to-object type. Here is the code:

int main (void) {
    void* a;
    int x;
    a = malloc(sizeof(int));
    x = 120;
    ((int)(*a)) = x;
    printf("%d",((int)*a));
    free(a);
    system("pause");
    return 0;
}

I see it like I am trying to assign the value of x in the memory block reserved for a. I want that the value stored in x be stored in the memory block of a. Can any1 help me?

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
Ruy
  • 121
  • 1
  • 1
  • 3

5 Answers5

9

You probably want to do:

void* a;
int x;
a = malloc(sizeof(int));
x = 120;
*(int*)a = x;
printf("%d", * (int*)a);
free(a);
karlphillip
  • 92,053
  • 36
  • 243
  • 426
4

You're making it too complicated. Just cast a to be an int *, or better yet declare a as int * to start with.

int x = 120;
int * a ;
// now just cast the result from malloc as int*
if((a = (int *)malloc(sizeof(int))) == NULL){ //ALWAYS check
   exit(-1);
}
*a = x;

There are slicker ways to do similar things in C++, but you appear to be primarily caught up in pointer syntax.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
3

Firstly, you must cast a to the appropriate pointer type and then de-reference it. Secondly, use a template- that's what they're for. Thirdly, malloc and free is baaaad, OK? Don't. If you think that this is good code, you need serious remedial C++. Fourthly, this is already done- boost::any serves this purpose.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 11
    This is why I hate "C/C++". – Puppy Aug 16 '11 at 16:12
  • 1
    @Charlie: yeah, but he didn't say "C ∩ C++" nor "C ∪ C++". – R. Martinho Fernandes Aug 16 '11 at 16:17
  • No, but he then uses stuff that's only C. – Charlie Martin Aug 16 '11 at 16:19
  • @Charlie: That doesn't make it C. He clearly states that he's going to put it in a class, in a class in C++, and he only tags C++. I think it's pretty clear what language he's discussing. – Puppy Aug 16 '11 at 16:22
  • it doesn't really answered my question.. malloc and free can be easily replaced. boost::any ins't even a C++ standard class. This problem has only the purpose of knowledge. Its important to know how things work before use a real class to understand whats going on on my program.. – Ruy Aug 17 '11 at 00:06
3

You need the cast as *(int*)(a) = x;.

Asha
  • 11,002
  • 6
  • 44
  • 66
0

There are other elegant ways to assign a variable of different types. For your current question you can follow the standard way as,

int* const a = new int;
//...
*a = 120;
//...
delete a;

Or just for this problem specifically,

int a = 120; // simple

[Note: In your current solution if you do,

*((int*)(a)) = x;

it might be breaking strict aliasing rule.]

iammilind
  • 68,093
  • 33
  • 169
  • 336