簡體   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