简体   繁体   English

取消引用“ void *”指针和强制转换不起作用

[英]Dereferencing ‘void *’ pointer and cast doesn't work

I try to do a project using multi-threading but I am not very familiar with void * and how to use it. 我尝试使用多线程来做一个项目,但是我对void *及其使用方法不是很熟悉。 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; 错误发生在行: th_nbr = tree->thread_nbr;

thread_nbr is an integer in my structure tree. thread_nbr是我的结构树中的整数。

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 * . tree的类型为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 . 因此,在取消引用时, tmp应该是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 . 注意:在这里,我将void指针重命名为p_tree

Dereference the void * first, into tmp then never reference tree again, always use tmp . 首先将void *引用到tmp然后再也不引用tree ,请始终使用tmp

The problem arises from trying to dereference a void * as if it were defined as a pointer to a t_tree struct. 问题来自尝试取消引用void * ,就像将其定义为指向t_tree结构的指针t_tree

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM