Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding char reference

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.

like image 213
nkint Avatar asked Feb 12 '12 23:02

nkint


People also ask

What is a character reference?

The personal reference, sometimes known as the character reference, is a brief assessment of you as an individual provided by someone who knows you outside of work. This should not be confused with the professional reference which is provided by a former or current employer.


1 Answers

The reason is that cout "knows" what to do with a char * value - it prints the character string as a NUL-terminated C string.

The same is not true of an int * value, so cout prints the pointer value instead.

You can force pointer value output by casting:

cout << static_cast<void *>(&letters[i]) << endl;
like image 91
Greg Hewgill Avatar answered Sep 28 '22 20:09

Greg Hewgill