简体   繁体   English

在 C 中将 * 变为 char 或 int

[英]Void * to char or int in C

I want to get any types of variables in my code, so I did a void * type to accept others.我想在我的代码中获取任何类型的变量,所以我做了一个 void * 类型来接受其他类型。 But I can get in char * but not in int values.但我可以进入 char * 但不能进入 int 值。 And I don't understand how I can did it.我不明白我是怎么做到的。 Here my code :这是我的代码:

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

In my main I did在我的主要我做了

insertion(maListe, 5);

it didn't work, but if I did this:它没有用,但如果我这样做:

insertion(maListe, "test");

It works.有用。 But I want both works !但我想要两部作品! Here my .h这是我的 .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;
};

Any idea ?任何的想法 ?

OK!好的! In your function void insertion(t_liste *liste, void *newValue) you are taking a argument of type void* .在您的函数void insertion(t_liste *liste, void *newValue)您使用的是 void* 类型的参数。 In the first case when you send a string(char *) the base address of the string is passed , so address is taken to newValue ,but in case when you pass a number,say 5 ,integer is passed to newValue where it expects an address.在第一种情况下,当您发送 string(char *) 时,将传递字符串的基地址,因此将地址带到newValue ,但是如果您传递一个数字,例如 5 ,则将整数传递给newValue ,它需要一个地址。

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

相关问题 C:将 void (*)(void *) 转换为 void (*)(char *) - C: Cast void (*)(void *) to void (*)(char *) 在C中将void *转换为char * - Casting void* to char* in C C:将 function 指针从通用输入 arg (void*) 类型转换为特定 (char*/int *) arg 和/或不同的返回类型,void,int - C: typecasting function pointers from generic input arg (void*) into specific (char*/int *) arg and/or different return types, void, int C —(void *)转换为int - C — (void*) to int 无效的问题*强制转换为int / char并替换结果 - Trouble with Void * casting to int/char and replacing results 为什么在 C 中 main() 之前没有数据类型(例如 void、int、char),就像在其他语言中一样? - Why does main() have no data type (such as void, int, char) before it in C, as it does in other languages? 没有完全理解 output 非常小的C 程序使用void*/char* 引用和int + 指针运算 - Don't fully understand the output of very small C program using void*/char* to refer to and int + pointer arithmetic C,“ void main(int argc,char * argv [0])”的含义是,请注意argv中的零 - the C, what does “void main (int argc, char *argv[0])”, note the zero in argv 无符号字符到char *和C中的int? - Unsigned char to char* and int in C? 为什么 C 中的 (char) + (char) = (int)? - Why (char) + (char) = (int) in C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM