mercredi 19 octobre 2016

Difference in the values displayed by the array when used int and char to define array [duplicate]

This question already has an answer here:

int main() {
    int array[7] = {'D','a','e','m','o','n'};
    for(int i = 0; i < 6; i++)
        cout << (array + i) << endl;

    cout << endl;
    cout << &array << endl;
    cout << "Hello World!\n";
}

When I do this I get the output as

0x7ffd24a67330
0x7ffd24a67334
0x7ffd24a67338
0x7ffd24a6733c
0x7ffd24a67340
0x7ffd24a67344

0x7ffd24a67330
Hello World!

But if I just change the array from int to char I have a change in the output

int main() {
    char array[7] = {'D','a','e','m','o','n'};
    for(int i = 0; i < 6; i++)
        cout << (array + i) << endl;

    cout << endl;
    cout << &array << endl;
    cout << "Hello World!\n";
}

This will display the string of characters instead of addresses.

Daemon
aemon
emon
mon
on
n

0x7fff9e645610
Hello World!

Why do I get two different outputs i.e addresses when I use int and values when I use char.

This part is out of context with the question but can somebody explain me why *array works when I define char array[10] and why it doesn't work when I define string array.

Aucun commentaire:

Enregistrer un commentaire