[英]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.