Monday, May 24, 2010

I need a little help in c++?

my first question is ::


1.why we use "*"(asterisk) when we declare variables of type pointer???


and the second one is ::


2.the output of this code is "value 1==10 / value2==20" could u tell me why? am a little bit confused.


int value1 = 5, value2 = 15;


int * mypointer;


mypointer = %26amp;value1;


*mypointer = 10;


mypointer = %26amp;value2;


*mypointer = 20;


cout %26lt;%26lt; "value1==" %26lt;%26lt; value1 %26lt;%26lt; "/ value2==" %26lt;%26lt; value2;


return 0;

I need a little help in c++?
* is dereferncing operator thing of letter which has address, *letter is content of the letter


== is assignment operator.


You may also contact a C expert to help you speeden up learning. Check websites like http://askexpert.info/
Reply:The asterisk indicates that you are declaring a pointer.


A pointer is just a 32-bit number that indicates a memory location.


If you omit the asterisk in %26lt;int * mypointer;%26gt; you will be declaring the variable of type integer, not its address.





The reason why you get that output is simple. Here is step by step.


Firs, you assign the values for value1 and value2 in this line:


int value1 = 5, value2 = 15;


Then you get the addres where value1 is stored and you save it with the pointer in this line:


mypointer = %26amp;value1; %26amp; means that you are getting the address, not the value.


After that you change the value stored in that address in this line:


*mypointer = 10; Actually you are changin the value of value1 not mypointer. * before mypointer indicates that you want to change the value.


The same goes for value2.


And that's why you get your output.
Reply:What you are asking is a complex(for a novice person) topic. I don;t think I could explain accuartely what you are asking for. I do however know of an excellent website that can explain it to you.





http://www.sparknotes.com/cs/pointers/wh...





Good Luck and feel free to email me with any more questions


No comments:

Post a Comment