Sunday, July 12, 2009

Difficult C++ pointer question, PLEASE HELP!!!!?

I'm reading this tutorial on c++, apparently when you define a pointer to be const, the address of that pointer can not be changed. However the below code defines a pointer as const called pointer and points to the address of variable a1, however i then give the pointer a new address (variable a2). I'm really confused because point was declared as a constant, yet a can change the address of the pointer and the program compiles with out any errors. can any body explain to whats happening and y my theory isn't working?





#include%26lt;iostream%26gt;


int main()


{


int a1 = 1, a2 = 2;


int const *point = 0;


point = %26amp;a1;


std::cout%26lt;%26lt;*point%26lt;%26lt;'\n';


point = %26amp;a2;


std::cout%26lt;%26lt;*point%26lt;%26lt;'\n';


system("pause");


return 0;


}





output:


--------


1


2


press any key to continue........

Difficult C++ pointer question, PLEASE HELP!!!!?
the compiler interprets


int const *point


as


const int *point


which mean it is a pointer to a constant integer.


change it to


int * const point


will cause the pointer point to not be changed.
Reply:The correct syntax for a constant pointer (that is a pointer that is constant itself rather than a pointer that points to a constant) would be:-





int* const point
Reply:The thing pointed to by the pointer is considered constant.
Reply:i asked the same question to myself just the other day, i worked on the problem for a week and resolved it but then i was diagnosed with a rare form of degenerative brain stem deterioration and i have short term memory loss as a result, but i knew i worked this out, i just cant remember so I'll let you know next year
Reply:Its because assigning a value and pointing to a variable are two different things. Its kind of like what the 1st person said.





For ex: point = %26amp;a1;


In this line, point is pointing to the variable a1.





Now try changing the value of a1 USING point.





ex:


*point = 5;


or


*point = 8;


or


*point = a2;





All will generate an error BECAUSE point was declared as a constant. Now try removing const from your declaration, all the above statements should execute correctly.


No comments:

Post a Comment