Ampersand in String
Feb 4, 2014 at 1:35pm Feb 4, 2014 at 1:35pm UTC
Hello everybody,
Until now, I thought that ampersand (&) is used to display the memory address.
For example:
1 2 3
int a[10] = { 1, 2, 3 };
cout << &a << endl; // Getting the address of array 'a' in pos [0] (a[0])
cout << &a[2] << endl; // The address of a[2]
Until now, as expected, the output will be addresses only.
But when the array is a string, it changes everything:
1 2 3 4
char b[10] = "Good Luck" ;
cout << &b << endl; // Until now, it's OK, address of b[0]
cout << &b[0] << " " <<endl;
/*OR*/ cout << &b[3] << endl; // NOW WHAT?!
The output is:
002DFA18
Good Luck
d Luck
As you can see, instead of getting the address of b[0] or b[3], the program outputs the string itself starting from the the position I wrote, and ends in '\0'.
Why is this happening?!
Feb 4, 2014 at 2:00pm Feb 4, 2014 at 2:00pm UTC
The reason is that the operator<< is overloaded for const char *
and other pointer differently. So if you provide a pointer to char the string is printed instead of the address.
Feb 4, 2014 at 2:08pm Feb 4, 2014 at 2:08pm UTC
If you want to print the address of a char* you can cast it to a void* before printing it.
cout << static_cast <void *>(&b[3]) << endl;
Feb 4, 2014 at 3:00pm Feb 4, 2014 at 3:00pm UTC
The reason is that the operator<< is overloaded for const char * and other pointer differently.
Sorry, I did not understand you.
If I use
strcpy(c, &b[3])
instead of "<<"- the action is similar: copy "d Luck" to c.
How can I "predict" when the program will output an address and when a value?
Feb 4, 2014 at 3:16pm Feb 4, 2014 at 3:16pm UTC
Let's phrase it so: The stream (cout) 'knows' what a string is and prints it accordingly. If a pointer to another type is provided it prints the value of the pointer.
See
http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
what types are 'known' by default
you can overload the operator<< anytime to extend the functionality.
How can I "predict" when the program will output an address and when a value?
read the documentation
Topic archived. No new replies allowed.