I have a C Program:
#include <stdio.h>
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;
}
Compiler produces an error:
error: invalid type argument of ‘unary *’ (have ‘int’)
Can someone explain what this error means?
Barebones C program to produce the above error:
#include <iostream>
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:
The master puts a shiny round stone inside a small box and gives it to a student. The master says: "Open the box and remove the stone". The student does so.
Then the master says: "Now open the stone and remove the stone". The student said: "I can't open a stone".
The student was then enlightened.
Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;
. Finally, you declared c
incorrectly. Since you assign it to be the address of a
, where a
is a pointer to int
, you must declare it to be a pointer to a pointer to int
.
#include <stdio.h>
int main(void)
{
int b=10;
int *a=&b;
int **c=&a;
printf("%d", **c);
return 0;
}
I have reformatted your code.
The error was situated in this line :
printf("%d", (**c));
To fix it, change to :
printf("%d", (*c));
The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.
In addition, the () was optional.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
EDIT :
The line :
c = &a;
must be replaced by :
c = a;
It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :
10
EDIT 2:
If you want to use a double * :
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Output:
10
Source: Stackoverflow.com