Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22015

(int vs. int*) - Why does the address always change with int* and not int in C++?

$
0
0

I am having a hard time understanding why the address of int* always changes while a regular int always stays the same. I assume since I'm using the 'new' keyword, the int* pointer will be dynamically allocated. What I don't understand is why my regular int always stays the same every time I run and compile.

int *ptr1 = new int(5);

std::cout << "ptr1 # = "<< *ptr1 << std::endl;
std::cout << "ptr1 & = "<< ptr1 << std::endl;

int *ptr2 = new int (10);

std::cout << "ptr2 # = "<< *ptr2 << std::endl;
std::cout << "ptr2 & = "<< ptr2 << std::endl;

int num {10};

std::cout << "num # = "<< num << std::endl;
std::cout << "num & = "<< &num << std::endl;

delete ptr1;
delete ptr2;

output 1:

ptr1 # = 5
ptr1 & = 0xf96d50
ptr2 # = 10
ptr2 & = 0xf96d80
num # = 10
num & = 0x61ff04

output 2:

ptr1 # = 5
ptr1 & = 0x1176d50
ptr2 # = 10
ptr2 & = 0x1176d80
num # = 10
num & = 0x61ff04

and so on...


Viewing all articles
Browse latest Browse all 22015

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>