Sunday 15 May 2011

c++ - strange behaviour of assigning char array to single char -



c++ - strange behaviour of assigning char array to single char -

// example: class constructor #include <iostream> #include <string> class test{ public: char* getcolor(){ homecoming color; } private: char color[5] = "blau"; }; int main () { test s; char *mychar = s.getcolor(); std::cout << mychar; homecoming 0; };

i don't understand how returns "blau" instead of b or else.

what i'm doing assigning starting pointer if char array single char pointer.

i'd understand why happens this. maybe it's because of std::cout getting values of type? instead of "b" says "blau"

there no difference between pointer single object , pointer first element of array. it's programmer know how should interpreted; or utilize friendlier types std::string.

when stream char* <<, assumes it's pointer first element of zero-terminated c-style string, , prints characters finds, starting one, until finds 1 0 value.

c++ arrays pointers

No comments:

Post a Comment