Tuesday, July 14, 2009

Pointer problem in c++ regarding user input?

I wrote a simple test case to see how pointers work in c++. I want to know how to take input from a user and store it in memory that was allocated using the new keyword. However my cout statements generate incorrect results.





#include%26lt;iostream%26gt;


using namespace std;





void main()


{


char* fname;





//allocate memory


fname = new char[20];





//allow up to 5 input characters


cin.get(fname,5);





//prints value without dereferencing?


cout %26lt;%26lt; fname %26lt;%26lt; endl;





//does not print addressess?


cout%26lt;%26lt;"index 0 address " %26lt;%26lt; %26amp;fname[0] %26lt;%26lt;endl;


cout %26lt;%26lt;"index 1 address " %26lt;%26lt; %26amp;fname[1] %26lt;%26lt;endl;


delete[] fname;


}





Say my input value is ‘ab’, the pointer fname which I thought holds the address to the allocated memory prints the value ‘ab’ without dereferencing. It seems that fname holds the actual value rather than an address. Furthermore %26amp;fname[0] and %26amp;fname[1] print the values ‘ab’ and ‘b’ respectively instead of the individual index addresses. If someone could comment on these 2 issues it would be helpful.

Pointer problem in c++ regarding user input?
when you send a char* for cout,it considers that


starting address of a string,and writes the string


to output for you,


in all cases you are sending a char* to cout,


he doesn't know what you mean, he thinks


you want a string of chars in output,





computers do what you say,not what you mean.
Reply:try modifying the following statement:





//allow up to 5 input characters


cin.get(fname,5);





to


cin.get(*fname,5);

blazing star

No comments:

Post a Comment