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
tinsidemethod(), after copyingmain()‘s objecttinto it. This doesn’t change anything inmain()‘s object since you never copy in the other direction.You should just access through the pointer and directly change the caller’s object:
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:
note that no cast is needed here, since
void *automatically converts toTest *in C.