What are the basics of pointers (*) and (&)addresses ?

I cant understand the concept of the ( & ) and ( * ) symbols in C++,

what is the difference between these three statements:
int n1 = n;
int & n2 = n;
int *n3 = & n;
and also what is the difference between these two statements:
int * q = p;
int n = *p;

Thanks in advance :)
1
2
3
4
5
6
int n1 = n; //n1 copies the value of n
int & n2 = n; //n2 is an alias of n, they are the same variable
int *n3 = & n; //n3 contains the address of where n is located in memory

int * q = p; //q copies the address contained in p
int n = *p; //n copies the value at the address stored in p 
Depending on context, each symbol could mean different things. In declarations, & means "reference", and * means "pointer". In expressions, & means "bitwise and" or "address-of", and * means "multiplication" or "indirection"

int n1 = n;
constructs an object of type int (this allocates some storage, typically 4 bytes), with name "n1", and initializes it with a copy of the value held in n

int & n2 = n;
assigns a new name "n2" to an existing object identified by the name "n".

int *n3 = & n;
constructs an object of type pointer-to-int (this allocates some storage, typically 4 bytes on a 32-bit platform, 8 bytes on 64-bit), names it "n3", and initializes it with the result of the expression "&n". That expression constructs a nameless pointer holding the address of n

int * q = p;
constructs an object of type pointer-to-int, names it "q", and initializes it with a copy of the value of p (here, p has to be a pointer too)

int n = *p;
constructs an object of type int, names it n, and initializes it with the result of the expression *p. This expression accesses the object pointed to by the pointer p.
I think
int & n2 = n; means that n is represented by n2.
because if you change the value of n2, n while change too.



int *n3 = & n; means that you get the address of the varible n and assign it to n3.
DANNY123 wrote:
I think
int & n2 = n; means that n is represented by n2.
because if you change the value of n2, n while change too.
n2 and n are the same variable; n2 is just an alias.
Topic archived. No new replies allowed.