why return function " *hey " has a strange behavior

why return function " *hey " has a strange behavior ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
char hy(char *a)
{ 
return *a; 
}
//char *a = &r  --->return char *a print d
char* hey(char *a)
{ 
return a;
}
 // char *a = &r ---- >return char*(a) print 'd' and some garbages
int main()
{
    char r = 'd';
   cout<< hy (&r)<<endl<< hey (&r)<<endl;
}

output
---------------
d
d?Jn�
Last edited on
You have undefined behavior because when you pass a char* into cout, cout interprets it as a NULL-terminated ('\0') string. Your char r is not a null-terminated string, so the program goes out of bounds when printing.
Last edited on
What did you expect to happen?

I expected get output like return ' hy ' function ,Ganado gave me a answer but i still don't understand why 'cout' interprets like that
English is not my mother tongue; please excuse any errors on my part.
Last edited on
hy returns the character pointed to by &r which is 'd'. When presented with a single character, cout outputs the character.

Before moving on to the hey function, let's consider what a string literal such as "d" is. It is constant array of 2 char (const char [2].) The first character is 'd' and the second (and last character) is the terminating nul character '\0'. In the context of a function call, (which cout << "d" involves) the string literal is treated as a pointer-to-const-char.

So, in order for cout to treat a string literal (or any C-style string) as one would expect, it treats it as a C-style string. This has the unfortunate effect of sometimes surprising people who unthinkingly expect the address contained by the pointer to be printed rather than the C-style string pointed to (although that isn't the case for you.)

So, as Ganado points out, r is not a C-style nul-terminated string, but a pointer-to-r is the same type as a pointer to a C-style string, so cout treats it as such, causing undefined behavior.

Don't send a pointer-to-char to cout if it isn't pointing to a nul-terminated string.
Last edited on
Yeah i should've given a more complete example.
To actually see the address of the variable, do cout << static_cast<void*>(hey (&r))

Also see http://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value
Topic archived. No new replies allowed.