Reputation: 369
I wrote two programs which prints out the variable the pointer p
points to:
First program:
#include <stdio.h>
int main (void){
int *p;
int a=5, q;
p=&a;
q=*p;
printf("%d", q);
}
Second program:
#include <stdio.h>
int main(void)
{
int a=5;
int*p;
p= (int*)&a;
printf("%d", *p);
return 0;
}
My question:
Both the programs print the value of a
which is 5
. However, the second program uses p=(int*)&a;
instead of just p=&a;
. Could someone please tell me the significance of (int*)
casting here?
Upvotes: 3
Views: 431
Reputation: 148
That is typecasting ,to tell the compiler that the value that is assigned to the pointer p that is &a is an integer type(int) but there it is of no use as &a return the address that is assigned to the variable a and it is always an integer.
Upvotes: 0
Reputation: 1054
Casting is a way for a programmer to tell the computer that, even though the computer thinks something is one type, we want to treat it as another type.
But here the cast is of no use as here a is an integer and thus address of a will need no cast here for integer pointer.
Upvotes: 3
Reputation: 15954
It's useless.
a
is an int
, so &a
is already a pointer to int
.
Upvotes: 2
Reputation: 134326
There is no significance, rather, this cast is superfluous and not required.
In your code, a
is of type int
, p
is of type int *
. Hence,
p= (int*)&a;
and
p= &a;
are same and the second one here is recommended.
Upvotes: 3