Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in C, C++

Tags:

c

pointers

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!?

like image 308
kunal18 Avatar asked Jul 30 '26 23:07

kunal18


2 Answers

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())

like image 189
phsym Avatar answered Aug 01 '26 16:08

phsym


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.

like image 31
Richard Chambers Avatar answered Aug 01 '26 15:08

Richard Chambers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!