Are these two equivalent?
int a=10;
int *p=a;
AND
int a=10;
int *p;
p=&a;
Does p hold address of a in both the cases!?
In the first case, the value of a is copied into p (which stores an address), so p points to the address 10.
In the second case, p points to the address of a.
There is a third case :
int a = 10;
int *p = malloc(sizeof(int));
*p = 10;
In this case, the value of a is copied into the address pointed by p (reserved by malloc())
In the first case
int a=10;
int *p=a;
The value contained in the variable a is put into the variable p. So the value of the variable p is 10.
In the second case
int a=10;
int *p;
p=&a;
The value in the variable a is 10 and the value in the variable p is the address of a.
In the first case even though the variable p is declared as a pointer to an int the value being put into the variable p is the value of the variable a, a value of 10. In the second case you are putting the address of the variable a into the variable p.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With