Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void* in c and pointers

Tags:

c

I am having trouble understanding the void* pointer in c. I've googled around but haven't really understood how to solve this specific problem:

typedef struct _Test{
   char* c;
}Test;


void method(void* test){
    Test t;
    t = *(Test*)test;
    t.c = "omg";
    printf(t.c); //WORKS
}

int main(){
Test t;
method(&t);
printf(t.c); //NOT WORKING,  prints nothing/random letters

return 0;}

Why? Or rather, best way to fix/get around this issue?

like image 330
Deragon Avatar asked Jan 31 '26 16:01

Deragon


2 Answers

You are changing the local object t inside method(), after copying main()'s object t into it. This doesn't change anything in main()'s object since you never copy in the other direction.

You should just access through the pointer and directly change the caller's object:

((Test *) test)->c = "omg";

or, you can make it a bit clearer by using a local pointer of the proper type, which might be what you were trying to do:

void method(void* test) {
    Test *t = test;
    t->c = "omg";
}

note that no cast is needed here, since void * automatically converts to Test * in C.

like image 56
unwind Avatar answered Feb 02 '26 07:02

unwind


You are defining a Test object in your method (created on the stack), then you point the given pointer there. After the method returns, the stack-allocated Test is gone.

Rewrite:

void method(void* test){
    Test *t;                     // defines a pointer to a Test object
    t = (Test*)test;             // casts the void pointer to a Test pointer
    t->c = "omg";                // assigns data to attribute
    printf(t->c); //WORKS
}

Of course, it can all be put in one line (excluding the printf()), removing the need for a stack-allocated Test pointer:

 void method(void* test){
        ((Test *)test)->c = "omg";
 }
like image 40
Bart Friederichs Avatar answered Feb 02 '26 05:02

Bart Friederichs