c++ - Why is my programs outputting values , 250? -
i new c++. having difficulty pointers, , cannot grasp full understanding of how pointers work. have experimented different programs utilising pointers dont understand why outputs way does. please me understanding why cout
outputs values 250. understand how processed values of reference value , both 12's 250?? can explain?? below code
#include <iostream> using namespace std; int main(){ int firstvalue = 12 , secondvalue = 6 ; int *ptr; ptr = &firstvalue; //address of firstvalue assigned ptr ptr = &secondvalue; *ptr = 250; // value pointed ptr = 250 cout << ptr << "\n"; cout << firstvalue << "\n"; cout << secondvalue << "\n"; cout << firstvalue << "\n"; }
program output :
address value // cant remember 12 250 12
int firstvalue = 12 , secondvalue = 6 ;
firstvalue
holds 12. secondvalue
holds 6. (bad habit imho. avoid comma, declare 1 variable per statement only. makes easier avoid errors later on when start declaring multiple pointers...)
int *ptr;
ptr
pointer-to-int holding indeterminate value @ point.
ptr = &firstvalue; //address of firstvalue assigned ptr
now ptr
holds address of firstvalue
.
ptr = &secondvalue;
now ptr
holds address of secondvalue
.
*ptr = 250; // value pointed ptr = 250
ptr
-- holding address of secondvalue
-- gets dereferenced (that asterisk *
here), , result -- secondvalue
-- gets new value assigned (250).
now firstvalue
holds 12, , secondvalue
holds 250.
cout << ptr << "\n"; cout << firstvalue << "\n"; cout << secondvalue << "\n"; cout << firstvalue << "\n";
and gets printed:
address value // cant remember 12 250 12
works expected.
Comments
Post a Comment