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?
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.
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";
}
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