Pointer-based strings

Hi there,

If I have the following:

1
2
3
4
5
char *s1 = "Hello";
char s2[]= "Hi";

cout << "s1 = " << s1;
cout << "s2 = " << s2;



1) This ouputs "Hello" and "Hi". Why doesn't it ouput the actual memory adress of the first character of "Hello"? Similarly with s2? Something like 0FH0x72?

2) Also, for s1, is "Hello" stored in a contiguous char array, or is it just floating around in memory? If not, how then does pointer subscript notation work? I know that s1 is a pointer and s2 is an array (and that the name s2 is a pointer to its first element), but what's the difference in the above statements? What's best to use? Please clarify :)

Thanks :)
Last edited on
1. operator<<() has an overload where, if the left hand operand is an std::ostream and the right hand operand is a char *, it interprets the pointer as pointing to a C string, and prints that.

2. The array s1 points to is allocated in a special part of the compiled binary by the compiler. This array cannot be deallocated (delete[] s1 will crash the program) and is available globally. In fact, the compiler may be smart enough s1 and s2 point to the same place, in the following example:
1
2
char *s1="Hello",
    *s2="Hello";

Back to your example, line 2 translates to this:
char s2[]={'H','i',0};
The array is allocated in the stack at run time, and (I think) filled from another array allocated next to the "Hello" from before.
Topic archived. No new replies allowed.