+ 1
Why char* and int* behave differently?
My question is simple: When I output the values of char* variable and int* variable, then why do they appear differently like in the following code: https://code.sololearn.com/cucAt7g5MW9m/?ref=app Or, is there any other way round to output their genuine value?
3 Answers
+ 6
Because name of array (string is array of chars) - is addres of first element of array.
When you initialise:
char* c = "c++"; // this equal - char c[] = {'c', '+', '+', '\0'};
You put in pointer "char* c" a addres of first element of const array of chars - "c++" - is 'c'.
And object of output "cout" is intellectual object. He interpretating this variable name with this type and selects the appropriate behavior and, in this case, output this like a string, terminated in NULL symbol '\0'.
When you initialise:
int* j = &i;
You take a addres of i (& - operator of taking address) and put it in pointer j.
And you output a value of pointer j. And he have a addres of i.
If you want to take value of i through the pointer, you need to use dereference operator *
std::cout << *j; //output - 6
+ 1
Hey ~ swim ~, so you meant that char* is treated like strings, then doesn't this treatment creates an ambiguity in the definition of pointers?
Also, it may lead to chaotic results.
0
Because cout is stupid. Use printf:
printf("%d", x);
Prints the value of x as a base 10 integer. x can be anything: char, int, pointer etc. (for 64-bit machines use "%lld" for pointers or "%p" for the hexadecimal address).
printf("%c", x);
Print x's character value. x can be anything (pointer, int, char).
printf("%s", x);
Treat x as a C-style string. Access the address x and start printing bytes, interpreted as characters. If x is a random number, or, in general, not a C style string, this will crash your program, because you'll be attempting to read memory that isn't yours.
cout cheats by looking at the type. If you cout any pointer type it acts like "%p", but with char * it acts like "%s"