Reputation: 643
struct limit{
int up;
int down;
};
void *x;
struct limit *l;
l->up=1;
l->down=20;
x=l;
cout<<x->up;
This is part of my code I am getting error in last line ‘void*’ is not a pointer-to-object type. I know last line in my code is wrong. I just want to know how to print up and down values using x
variable.
Upvotes: 1
Views: 9669
Reputation: 42133
In this part:
struct limit *l;
l->up=1;
l->down=20;
you are dereferencing uninitialized pointer l
, which results in undefined behavior. However, even if you initialized it properly, after you assign it to void*
, you can not dereference void
pointer:
void* x = l;
cout<< x->up;
you need to explicitly cast it back to struct limit*
:
void* x = l;
struct limit * y = static_cast<struct limit*>(x);
cout << y->up;
or yet even better: avoid using void*
at first place.
Since you mentioned that you're doing this because of pthreads, then this answer will help you :)
Upvotes: 5