char color[]= "white";
color is an array of 6 characters. One for each character in "white" and one for the null terminator at the end to signify the end of the string. This line is the same as saying
char color[6] = "white";
So when you do this:
char* pColor = &color[10];
You are getting a pointer to color[10]. Since color is only 6 entries big, there is no 10 entry. Therefore, pColor is a bad pointer.
You are doing the same thing here:
pList = &list[NUMBER_LIST];
'list' only has 3 elements (ie: index [2] is the maximum index). So if you get a pointer to index [3], then that is a pointer to outside the array. IE: it's a bad pointer.
If you want a pointer to the start of the array, then use index 0:
1 2 3
|
char* pColor = &color[0]; // now pColor points to the first element in the color array.
int* pList = &list[0]; // and pList points to the first element in the list array.
|
Although, this can be shortcutted because array names can be implicity cast. So you can just do this:
1 2 3
|
char* pColor = color; // same as = &color[0]
int* pList = list; // same as = &list[0]
|
Also, 1 pointer = 1 memory address. When you try to print the addresses on line 30.. you can't loop through pList and pColor as if they were arrays, because they're not arrays. They're a single pointer.
What you're actually doing there is looping through the array they point to.
1 2 3 4 5 6 7 8 9
|
int* pList = list; // pList points to the list array
for(int i = 0; i < 3; ++i)
{
cout << pList[i]; // <- this will not print an address, but will print the contents
// of the list array.. just as if you were printing list[i]
}
cout << pList; // <- this will print an address
|
char pointers also need to be cast because they are interpretted as strings by iostream. So you'll have to cast them to some other kind of pointer to actually have the address printed.
1 2
|
cout << pColor; // will print "white"
cout << (void*)(pColor); // will print the address of the color array
|