Pointers + Arrays

So, I have been reading over this. http://www.cplusplus.com/doc/tutorial/pointers
And have come across a question.

1
2
3
4
5
6
7
        const char * terry = "hello";
	if (terry == &terry[0])
	{
		cout << "TRUE.";
	}
	cout << endl << terry;
	cout << endl << &terry[0];


The page says "It is important to indicate that terry contains the value 1702, and not 'h' nor "hello", although 1702 indeed is the address of both of these."

I don't understand why then it outputs (Visual studios 2010)

TRUE.
hello
hello

Also. & the reference operator. Why does &terry[0] not output the memory address of where 'h' is stored, but instead hello?

If anyone could explain that to me, that would be great!
On line 2: both are pointer to the first element, so they're equal.

The reason why the string and not the address appears in the output lies in the nature of the stream (respectively the operator<<). if you provide a certain type (like const char*) it knows what to do: output the string (it assumes that the address points to a 0 terminated string).

if you write that:

cout << endl << (void *) terry;

the stream doesn't know anymore what to do with the data and prints the address.
Last edited on
use parentheses to output address:
cout << &(terry[0]);
Also. & the reference operator.


The & in this case is the "address of " operator, and is not the same thing as a reference.

Google.
@majidkamali1370
the parentheses won't make any difference
@majidkamali1370
use parentheses to output address:
cout << &(terry[0]);


Even if you will use two pairs of parentheses in any case the string literal will be outputed, not the address.:)

cout << &((terry[0]));

The output is

hello
Topic archived. No new replies allowed.