pointers and string literals

Hello. In the code below, foo is a pointer that points to the first element of "hello", which is 'o'. Then how can foo[4] be valid? I don't understand why foo also points to a sequence of characters.
1
2
3
4
5
6
7
8
9
int main()
{
	const char * foo = "hello";
	cout << *(foo + 4) << endl; //o
	cout << foo[4] << endl; //o

	cin.get();
}
(1)
The first element of "hello" is 'h'.

(2)
Using square brackets (what you did on line 5) is syntactic sugar for a combined pointer offset and indirection (what you did on line 4). That is, the two lines are identical.

It is also why arrays are conveniently numbered from zero.

    *(foo+0) is foo[0],
    *(foo+1) is foo[1],
    etc.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.