+ 1

[C++] ¿What is the difference between this expressions?

I am at the dynamic memory part of C++, and I'm still quite confused about pointers. I have 2 doubts/Questions. CASE 1/Q 1: Expression 1: int * p; Expression 2: int *p; ¿Are they the same? --------------------- CASE 2/Q 2: Expression 1: int * p; p = 5; Expression 2: int * p; *p = 5; or int *p; *p = 5; ¿What does the pointer do when assigned with * here? ¿Whats the difference between asign with * and without *?

1st Feb 2018, 1:14 PM
Brian
Brian - avatar
3 Antworten
+ 11
IIRC: int * p, int* p and int *p is the same. They all declare a pointer p which can be used to store address of integer variables. int *p; *p = 5; and int* p; p = 5; is not the same. A pointer stores the address of a variable. * (point-to) operator tells the program to point to the variable whose address is stored in the pointer. When we do p = 5; we store the value 5 into the pointer. When we do *p = 5; we store the value 5 into an integer variable whose address is stored in the pointer. E.g. int x = 5; // integer variable x stores value 5. int *p; p = &x; // p now stores address of x. (& operator returns address of a variable) std::cout << p; // print address of x. std::cout << *p; // print value stored in x.
1st Feb 2018, 1:23 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Try looking into this code written by ValentinHacker, it might help at getting to understand how & and * works. https://code.sololearn.com/c7mW3DQoz3m0/?ref=app
1st Feb 2018, 1:28 PM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Thanks Hatsy!
1st Feb 2018, 1:24 PM
Brian
Brian - avatar