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?
After declaration, we store the address of variable 'data' in a void pointer variable, i.e., ptr. Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable.
Some Interesting Facts: 1) void pointers cannot be dereferenced. For example the following program doesn't compile.
A void pointer is pointer which has no specified data type and the void pointer can be pointed to any type. If needed, the type can be casted as : int **q =(int **)&vptr. In given code, vptr is a void pointer and 'i' is integer variable. But vptr assigned the address of integer variable without typecasting.
The pointer to void can be used in generic functions in C because it is capable of pointing to any data type. One can assign the void pointer with any data type's address, and then assign the void pointer to any pointer without even performing some sort of explicit typecasting.
You probably want to do:
void* a;
int x;
a = malloc(sizeof(int));
x = 120;
*(int*)a = x;
printf("%d", * (int*)a);
free(a);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With