So…I have the following code:
int main(void)
{
const char *s="hello, world";
cout<<&s[7]<<endl;
return 0;
}
and it prints “world”…however I don’t understand why this:
int main(void)
{
const char *s="hello, world";
cout<<s[7]<<endl;
return 0;
}
only will print “w” (all I changed is got rid of the ampersand), but I thought that was the “address of” operator…which makes me wonder why you need it and what it’s function is?
s[7]is the character'w', so&s[7]becomes the address of the character'w'. And when you pass an address ofchar*type tocout, it prints all characters starting from the character to the null character which is end of the string i.e it continues to print characters from'w'onward till it finds\0. That is howworldgets printed.Its like this,
Output:
However, if you want to print the address of
s[7], i.e value of&s[7], then you’ve to do this:Now we pass an address of
void*type, socoutwouldn’t be able to infer what it used to infer withchar*type address.void*hides all information regarding the content of the address. Socoutsimply prints the address itself. After all, that is what it gets at the most.Online demonstration : http://www.ideone.com/BMhFy