erreur: argument de type non valide de ‘unary *’ (have ‘int’)

J’ai un programme C:

#include  int main(){ int b = 10; //assign the integer 10 to variable 'b' int *a; //declare a pointer to an integer 'a' a=(int *)&b; //Get the memory location of variable 'b' cast it //to an int pointer and assign it to pointer 'a' int *c; //declare a pointer to an integer 'c' c=(int *)&a; //Get the memory location of variable 'a' which is //a pointer to 'b'. Cast that to an int pointer //and assign it to pointer 'c'. printf("%d",(**c)); //ERROR HAPPENS HERE. return 0; } 

Le compilateur produit une erreur:

 error: invalid type argument of 'unary *' (have 'int') 

Quelqu’un peut-il expliquer ce que cette erreur signifie?

Puisque c contient l’adresse d’un pointeur entier, son type doit être int** :

 int **c; c = &a; 

L’ensemble du programme devient:

 #include  int main(){ int b=10; int *a; a=&b; int **c; c=&a; printf("%d",(**c)); //successfully prints 10 return 0; } 

Programme Barebones C pour produire l’erreur ci-dessus:

 #include  using namespace std; int main(){ char *p; *p = 'c'; cout << *p[0]; //error: invalid type argument of `unary *' //peeking too deeply into p, that's a paddlin. cout << **p; //error: invalid type argument of `unary *' //peeking too deeply into p, you better believe that's a paddlin. } 

ELI5:

 You have a big plasma TV cardboard box that contains a small Jewelry box that contains a diamond. You asked me to get the cardboard box, open the box and get the jewelry box, open the jewelry box, then open the diamond to find what is inside the diamond. "I don't understand", Says the student, "I can't open the diamond". Then the student was enlightened. 

J’ai reformaté votre code.

L’erreur était située dans cette ligne:

 printf("%d", (**c)); 

Pour résoudre ce problème, passez à:

 printf("%d", (*c)); 

Le * récupère la valeur d’une adresse. Le ** récupère la valeur (une adresse dans ce cas) d’une autre valeur à partir d’une adresse.

De plus, le () était optionnel.

 #include  int main(void) { int b = 10; int *a = NULL; int *c = NULL; a = &b; c = &a; printf("%d", *c); return 0; } 

MODIFIER :

La ligne :

 c = &a; 

doit être remplacé par:

 c = a; 

Cela signifie que la valeur du pointeur “c” est égale à la valeur du pointeur “a”. Donc, “c” et “a” indiquent la même adresse (“b”). La sortie est:

 10 

EDIT 2:

Si vous souhaitez utiliser un double *:

 #include  int main(void) { int b = 10; int *a = NULL; int **c = NULL; a = &b; c = &a; printf("%d", **c); return 0; } 

Sortie:

 10 

Une fois que vous avez déclaré le type d’une variable, vous n’avez pas besoin de la convertir dans ce même type. Vous pouvez donc écrire a=&b; . Enfin, vous avez déclaré c incorrectement. Comme vous l’assignez à l’adresse d’ a , où a est un pointeur sur int , vous devez le déclarer comme un pointeur sur un pointeur sur int .

 #include  int main(void) { int b=10; int *a=&b; int **c=&a; printf("%d", **c); return 0; }