C++ storing a string in a pointer.

  • Context: Comp Sci 
  • Thread starter Thread starter Mr Virtual
  • Start date Start date
  • Tags Tags
    C++ String
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 26K views
Mr Virtual
Messages
218
Reaction score
4

Homework Statement



If I write:

char* Name="Computer";
count<<Name[0]; //Output: C
count<<Name[2]; // Output: M

what do the above lines mean? How can a pointer store a string? And why is it acting like an array? Either it is a simple concept that I have forgotten or it is a new concept that I have yet to study.


The Attempt at a Solution



Here, Name is a pointer of char type i.e. it can store the address of a char type variable. We cannot assign a character to a pointer. Then how is it still correct to assign a string to a pointer. What is happening here?
Please Help!

Thanks
Mr V
 
Physics news on Phys.org
You're using a shorthand notation.

When the compiler sees quote marks, it actually reserves space in your executable's data segment for the stuff inside the quotes, and then initializes the pointer Name to point to the first character of it. There's no deeper magic going on.

- Warren
 
Ok, so the compiler reserves a temporary sapce for the string and makes the pointer point at the address of the first character. But what does it mean if I write

count<<Name[1];

and it gives 'O' as output, if the string entered was "COMPUTER"?

Is this equivalent to: count<<Temp[1];
So C++ actually says that if you assign a character to a pointer, then it is an error, but if you assign a string, you are not actually assigning it to the pointer but creating a space to store the string.

There is one more problem:
If Name is storing the address of the first character of the string, how come I get "COMPUTER" as output when I write:

count<<Name;

It should show me the address of where 'C' is stored, but it gives me a string. Are all the pointer rules bent for this type of thing. Can you direct me to a site which provides all the rules for such a case and explains them.

Thanks for your answers.

Mr V
 
When I write:

count<<*Name; //Output: C

Which means it "is" storing the address of the first character entered. But why does it display the string in the case I have shown in my previous post above?

Mr V
 
Because the 'C' rules for outputing a string are, start at the first character and continue until you get a '\0'.
Strings are just areas of memory with a 0 byte at the end.

If you want to output just the first letter you would do something like,
char c = Name[0];
count << c;

or possibly
count << (char)Name[0]
 
Thanks. I have now understood the answer to my question.

Thanks again for your answers.

Mr V