void * 到 C 中的 char 或 int

Void * to char or int in C

我想在我的代码中获取任何类型的变量,所以我做了一个 void * 类型来接受其他类型。但是我可以得到 char * 但不能得到 int 值。我不明白我是怎么做到的。 这是我的代码:

void    insertion(t_liste *liste, void *newValue) {
  t_element *new = malloc(sizeof(void *));
  int i;
  int *j = &i;

  if (liste == NULL || new == NULL) {
    exit(EXIT_FAILURE);
  }
  if (newValue == j || (char *)newValue) {
     new->value = newValue;
     new->suivant = liste->premier;
     liste->premier = new;
     liste->taille++;
     new->index = liste->taille;
  }
}

主要是我做了

insertion(maListe, 5);

它没有用,但如果我这样做:

insertion(maListe, "test");

有效。 但我想要两个作品! 这是我的.h

typedef struct s_element t_element;
typedef struct s_liste t_liste;

struct s_element{
  int           index;
  void          *value;
  t_element     *suivant;
  t_element     *precedent;
};

struct s_liste{
  t_element     *premier;
  t_element     *dernier;
  int           taille;
};

有什么想法吗?

好的!在您的 function void insertion(t_liste *liste, void *newValue) 中,您采用了 void* 类型的参数。在第一种情况下,当你发送一个字符串(char *)时,字符串的基地址被传递,所以地址被带到 newValue,但是如果你传递一个数字,比如 5,整数被传递到 newValue 它需要一个地址。