c++ - In char x[10]="hello" , why cout<<x; doesn't print out the array's address? -
this question has answer here:
as in
int x[3] = {1, 2, 3, 4}; cout<<x;
would print out x address. if choose character array,
char x[10]="hello";
it prints out string
hello
and let's compiler smart enough understand in case of char array , point less print out address , prints out string instead, how print char array address?
and consider statement
char *ptr = "hello";
why legal, aren't pointers supposed store address?
it prints "hello" because operator <<
has overload const char*
(which you're passing if pass x
) prints out single char
, moves next char
until nul-character found. "hello" has compiled-added nul-character @ end, string "hello\0".
to address can cast void*
remove overload of const char*
:
reinterpret_cast<const void*>(x)
why legal, aren't pointers supposed store address?
yes, that's ptr
storing. when assign pointer "hello" const char[]
ptr point [0]
of array. note though in case conversion first has made const char*
char*
has been deprecated years , since c++11 illegal because trying edit pointee through char*
lead undefined behaviour. compilers still allow though while should emit error.
Comments
Post a Comment