I’ve written this simple script to understand what a reference is, and I’m getting stuck on the char array.
int numbers[5] = {3, 6, 9, 12, 15};
for (int i = 0; i < 5; i++)
{
cout << numbers[i] << endl;
cout << &numbers[i] << endl;
}
cout << "--------------" << endl;
char letters[5] = {'a', 'b', 'c', 'd', 'e'};
for (int i = 0; i < 5; i++)
{
cout << letters[i] << endl;
cout << &letters[i] << endl;
}
and this is the output:
3
0xbffff958
6
0xbffff95c
9
0xbffff960
12
0xbffff964
15
0xbffff968
--------------
a
abcde
b
bcde
c
cde
d
de
e
With the int array, when I use &numbers[i], I receive a strange number that is a memory location. This is ok; it’s exactly what I’ve understood.
But with char, I don’t understand why I have this output.
The reason is that
cout“knows” what to do with achar *value – it prints the character string as a NUL-terminated C string.The same is not true of an
int *value, socoutprints the pointer value instead.You can force pointer value output by casting: