Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to a dereferenced void pointer

Tags:

c

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?

like image 794
Ruy Avatar asked Aug 16 '11 16:08

Ruy


People also ask

How do you assign a value to a void pointer?

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.

Can a void pointer be dereferenced?

Some Interesting Facts: 1) void pointers cannot be dereferenced. For example the following program doesn't compile.

How do you assign a void pointer VPTR to an integer pointer PTR?

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.

Can a void pointer point to a function?

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.


2 Answers

You probably want to do:

void* a;
int x;
a = malloc(sizeof(int));
x = 120;
*(int*)a = x;
printf("%d", * (int*)a);
free(a);
like image 58
karlphillip Avatar answered Oct 22 '22 21:10

karlphillip


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.

like image 30
Charlie Martin Avatar answered Oct 22 '22 19:10

Charlie Martin