picstand picstand - 3 months ago 360
C Question

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

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?

Answer

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

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