Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confuse about & and * in the C++

I just learned C++, and I don't understand the below:

The code part:

int *i = new int;
*i = 0;
int &j = *i;
j++;

Question: which the meaning of the last line: j++?
Answer: Increments the value pointed to by i by one.

My confusion:
I am not sure the meaning of int &j = *i;

What's the relationship between j and pointer i? j is the pointer or other?

like image 821
LiLian Avatar asked Oct 15 '25 15:10

LiLian


1 Answers

I am not sure the meaning of int &j = *i; what's the relationship between j and pointer i? j is the pointer or other?

int &j is declaring a variable j, of type int&, or integer reference (see What is a reference variable in C++?).

int &j = *i is assigning the value at address i to the reference variable j. So whenever you modify j, you'll be modifying *i (and vice versa).

See also: What are the differences between a pointer variable and a reference variable in C++?

like image 184
scohe001 Avatar answered Oct 17 '25 04:10

scohe001



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!