I try to do a project using multi-threading but I am not very familiar with void *
and how to use it. I have the problem in this function :
void *find_way_out(void *tree)
{
int i;
t_tree *tmp;
t_tree **road;
int j;
int th_nbr;
th_nbr = tree->thread_nbr;
j = 0;
road = xmalloc(sizeof(t_tree));
i = 0;
tmp = (t_tree *)tree;
road[j] = tmp;
tmp->visited[th_nbr] = 1;
while (1)
{
while (tmp->leaf[i] != NULL)
{
printf("room : %s && room next %s\n", tmp->room, tmp->leaf[i]->room);
if (tmp->leaf[i]->visited[th_nbr] == 0)
{
road[++j] = tmp;
tmp = tmp->leaf[i];
tmp->visited[th_nbr] = 1;
i = -1;
printf("going to room-> %s\n", tmp->room);
}
if (tmp->type == END)
{
printf("find end...\n");
pthread_exit(&j);
}
i++;
}
tmp = road[j];
if (--j == -1)
pthread_exit(0);
i = 0;
printf("backing to room %s\n", tmp->room);
}
pthread_exit(0);
}
The error is at line : th_nbr = tree->thread_nbr;
thread_nbr
is an integer in my structure tree.
When I compile I have these errors :
sources/find_way.c:21:16: warning: dereferencing ‘void *’ pointer
th_nbr = tree->thread_nbr;
^
sources/find_way.c:21:16: error: request for member ‘thread_nbr’ in something not a structure or union
You have an idea to fix it? Thanks.
In your case, at the time of dereferencing,
th_nbr = tree->thread_nbr;
tree
is of type void *
.
You need to move
tmp = (t_tree *)tree;
before
th_nbr = tmp->thread_nbr; //tree changed to tmp
so that, at the point of dereferencing, tmp
should be a pointer of type tree
.
You will need to cast first.
void *find_way_out(void *p_tree)
{
int i;
t_tree *tree = (t_tree*) p_tree;
t_tree *tmp;
t_tree **road;
int j;
int th_nbr;
th_nbr = tree->thread_nbr;
Note: Here I renamed the void pointer to p_tree
.
Dereference the void *
first, into tmp
then never reference tree
again, always use tmp
.
The problem arises from trying to dereference a void *
as if it were defined as a pointer to a t_tree
struct.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.