chonglawr chonglawr - 1 year ago 81
C Question

How can I assign a struc to a void pointer passed through the paramters?

In my code I have a struc

struct Test {
int a;
int b;
char c;

With my function:

int TestFunction(void* ptr){
struct Test test;
test.a = 0;
test.b = 1;

return 0;

Now to link the temp struc to the void ptr I passed in I have

struct Test* temp = (struct Test*)ptr;
struct Test test = *temp;

Is this the correct way to link strucs with void ptrs? Is there an easier way?

Answer Source

Since you want to be able to modify the struct pointed to, your sample code is not appropriate. What it does is create a local copy of the pointed-to struct and modifies the local copy instead of the original object.

What you want to do, rather, is this:

int TestFunction(void *ptr) {
    struct Test *test = ptr;
    test->a = 0;
    test->b = 1;

    return 0;

The a->b syntax is equivalent to (*a).b, meaning that it refers to whatever test points to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download