Pointer confusion. Please explain :)

Today I've learned some concepts about Pointer in C++ and I have a confusion in this code snippet and its result.

Source Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Pointer array
#include <iostream>
using namespace std;

void main () {
	char * say = "Hello";		
	//
	cout << "say = " << say << endl;
	cout << "&say = " << &say << endl;
	cout << "*say = " << *say << endl;
	cout << "say[1]=" << say[1] << endl;
	cout << "*(say+1)=" << *(say+1) << endl;	
	//
	cout << endl << endl;
	for (int i=0; i<5; i++) {
		cout << "say["<< i <<"]=" << say[i] << endl;	
	}
	//
	cout << endl << endl;
	for (int i=0; i<5; i++) {	
		cout << "&say["<< i <<"]=" << &say[i] << endl;
	}
}


And this is the result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
say = Hello
&say = 0012F3A4
*say = H
say[1]=e
*(say+1)=e

say[0]=H
say[1]=e
say[2]=l
say[3]=l
say[4]=o

&say[0]=Hello
&say[1]=ello
&say[2]=llo
&say[3]=lo
&say[4]=o


I try to understand why it gave this result, but I cannot understand the section in bold.

Please explain it for me.

Thanks very much,
Nichya.
Hi Nichya,

In the code you bolded, cout is reading from a specific memory address pointed to by the pointer say. With each cycle through the for loop, cout starts reading from the next allocated memory element, until it reaches the end of the pointers memory chunk.

Hope this helps.
cout thinks that pointers to char are null-terminated C strings so it shows the contents of the original string rather than the memory address. You can cast it to a void* to get pointer output
Topic archived. No new replies allowed.