JacKeown
JacKeown

Reputation: 2890

How does &x vary from x if x is a pointer?

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?

Upvotes: 3

Views: 415

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

s[7] is the character 'w', so &s[7] becomes the address of the character 'w'. And when you pass an address of char* type to cout, 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 how world gets printed.

Its like this,

const char *s="hello, world";
const char  *pchar = &s[7]; //initialize pchar with the address of `w`
cout<< pchar <<endl; //prints all chars till it finds `\0` 

Output:

world

However, if you want to print the address of s[7], i.e value of &s[7], then you've to do this:

cout << ((void*)&s[7]) << endl; //it prints the address of s[7]

Now we pass an address of void* type, so cout wouldn't be able to infer what it used to infer with char* type address. void* hides all information regarding the content of the address. So cout simply prints the address itself. After all, that is what it gets at the most.

Online demonstration : http://www.ideone.com/BMhFy

Upvotes: 10

jwismar
jwismar

Reputation: 12258

s[7] is a character. (You can index into pointers to an array as if it was just the name of the array).

&s[7] is a pointer to the character at index 7. it's type is char*, so the stream inserter treats it like a char*.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

Your title doesn't match your question... at all.

Since s is a pointer to char (aka C-style string), s[7] is a char. Since s[7] is a char, &s[7] is a pointer to char (aka C-style string).

Upvotes: 4

Related Questions