繁体   English   中英

在 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;
};

任何的想法 ?

好的! 在您的函数void insertion(t_liste *liste, void *newValue)您使用的是 void* 类型的参数。 在第一种情况下,当您发送 string(char *) 时,将传递字符串的基地址,因此将地址带到newValue ,但是如果您传递一个数字,例如 5 ,则将整数传递给newValue ,它需要一个地址。

暂无
暂无

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

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