Saturday, May 22, 2010

Basic C++ help plz?

void getNumber(int %26amp;n)


{


cout %26lt;%26lt; "Enter a number: ";


cin %26gt;%26gt; n;


}





In this function, the parameter n is a reference variable. Rewrite the function so that n is pointer.





How do I change the n to a pointer?


Thanks.

Basic C++ help plz?
You change the function declaration from:





void getNumber(int %26amp;n)





to:





void getNumber(int *pn)





Now pn is a pointer to an integer. Now instead of using n directly, such as:


n = 3; or x = n/2; you have to dereference the pointer. The equivalent statements would be:


*pn = 3; or x = *pn/2;





What's happening is pn holds the address of an integer. To get the contents (i.e. the actual integer value) you use the * operator.





You can see the difference in the following output:





cout %26lt;%26lt; "pointer address: " %26lt;%26lt; pn %26lt;%26lt; endl;


cout %26lt;%26lt; "integer value: " %26lt;%26lt; *pn %26lt;%26lt; endl;





Pointers are useful for dealing with blocks of data (e.g. an array of 100 integers):


void func(int *block, int block_size)


{


for (int i = 0; i != block_size; ++i)


{


cout %26lt;%26lt; *(block + i) %26lt;%26lt; ", "; // use ith integer from block


}


}





They are also useful for optional data.


void func2(int v1, int *option)


{


cout %26lt;%26lt; "v1: " %26lt;%26lt; v1 %26lt;%26lt; endl; // use v1


if (option != NULL)


cout %26lt;%26lt; "option: " %26lt;%26lt; *option %26lt;%26lt; endl;


}
Reply:By use of the dereferencing operator, '*'.





Pointer creation =%26gt; char * My_Char_Pointer;





To initialize a pointer =%26gt;





My_Char_Pointer = %26amp; other_char;





To change the data stored at the pointer's address =%26gt;





*My_Char_Pointer = Yet_another_Char;





I hope this helps you out. There is a link to a good C++ reference below, if you need more information. Pivy.

magnolia

No comments:

Post a Comment