strange output with c style strings

Hey guys I know it's better to use std::string and all that but I am messing around and noticed a string bug in my code,

as you see when I print e I was expecting l to be printed since e points to a char with l in it,instead it prints two l's and even weirder it then prints a ) after the l's,I thought maybe this was because char pointer e would have to know where the character ends but if that was the case shouldn't it print everything to the null terminator of the *p string

also how come when you do this with an int for example int* p_i = &number it will always produce the number where as when I did it with a char pointer I got weird results

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int main()
{
    char *p = "hello world";
    char *c = &p[2];  // here we are deferencing the memory pointed to in a way
                      // because we are not printing out the third index[2] but assigning the c char pointer
                      // to the string *p but starting at the offset of [2] which will be y baby
    char *d = &p[2];
    char u = p[2];
    char *e = &u;

    cout << u << endl; // prints l
    cout << c << endl; // prints llo world
    cout << e << endl; // prints ll) ?

}
e is a char-pointer. When a char-pointer is passed to cout, you get out every character from that memory location onwards, until a zero is found.

u is a char, somewhere in memory. It has the value 'l'. u is NOT a char pointer into the string "hello world". u could be anywhere in memory. It appears that in your case, next to it is a value 'l' , and then a value ')' , and then a zero.

I thought maybe this was because char pointer e would have to know where the character ends
It certainly does not know that.

shouldn't it print everything to the null terminator of the *p string
e is not pointing into the string. e is pointing at the char u, and the char u is not part of the string.
Last edited on
And by the way char *p and char *c should be const qualified variables. If you were using a modern C++ compiler properly configured it would be pointing this out to you.

Topic archived. No new replies allowed.