0

What is the difference between declaring a variable and declaring a pointer?

Hi guys, I'm at learning about pointers in the C++ course, and I have the following question. Code 1: int main(){ int num = 42; int *p = &num; cout << *p; } Code 2: int main(){ int num = 42; int p = num; cout << p; } With both code syntaxes I get the same outcome, and they both store 42. I know the pointer is about storing the memory address, but I don't really see/get it. Can someone explain what it does, and what the fundamental difference between these codes are any further? Thnx for the effort!

21st Aug 2024, 8:48 AM
Keetie
2 Respuestas
+ 1
in Code 1, both num and p access the same memory location of 42. changing num affects p and changing p affects num. in Code 2, p is just a copy of num. p will store 42 in a different memory location than the 42 of num. changing num will not affect p and changing p will not affect num. https://sololearn.com/compiler-playground/ceBevf5CcqKY/?ref=app
21st Aug 2024, 11:45 AM
Bob_Li
Bob_Li - avatar
0
Declaring a variable creates a temporray space whereas declaring a pointer locate content at a fixed address which can only accessed by pointer
21st Aug 2024, 10:22 AM
RISHABH
RISHABH - avatar