Deragon
Deragon

Reputation: 305

void* in c and pointers

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?

Upvotes: 2

Views: 3629

Answers (4)

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

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);

return 0;}

Upvotes: 1

unwind
unwind

Reputation: 400129

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.

Upvotes: 11

Bart Friederichs
Bart Friederichs

Reputation: 33573

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

Upvotes: 3

Martin Green
Martin Green

Reputation: 1054

t in method()'s scope shadows t in main()'s, which never gets touched, thus containing undeterminable data when you call printf() with it.

Upvotes: 1

Related Questions