C++ Beginner: Array of type char vs Array of type int

This is my first post. As a beginner of learning C++, I am trying to understand the difference between an array of type char and an array of type int. I wondered whether someone could answer the following:

1. I expect the following line should return an address of the first index of an array but it returns a whole string.
 
cout << "Print char array: " << array << endl;


2. I expect the following line should return letter 'b' but it returns '98' which is an ASCII code for letter 'b'.
 
cout << "Print char array[0]+1: " << array[0]+1 << endl;


3. It seems like I have some misunderstanding about array with 'string' type or array with 'char' type, could someone suggest any good links to read about the specific topic or some keywords I can look up?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void IntArray () {
    int array[5] = {5,6,7,8,9};

    cout << "Print int array: " << array << endl;
    cout << "Print int array[0]: " << array[0] << endl;
    cout << "Print int array[0]+1: " << array[0]+1 << endl;
}

void CharArray () {
    char array[5] = {'a', 'b', 'c', 'd', '\0'};

    cout << "Print char array: " << array << endl;
    cout << "Print char array[0]: " << array[0] << endl;
    cout << "Print char array[0]+1: " << array[0]+1 << endl;
}


The result of executing the above two functions:
1
2
3
4
5
6
Print int array: 0xbfd66a88
Print int array[0]: 5
Print int array[0]+1: 6
Print char array: abcd
Print char array[0]: a
Print char array[0]+1: 98


Thank you so much for help!
1. When you try to print the address of the char array, the compiler thinks that it's a string and prints the array as a string instead of printing the address.
This only happens with char arrays.
You can force it to print the address by casting it to void*:
cout << "Print char array: " << static_cast<void*>(array) << endl;

2. I did some testing an apparently, adding an integer to a character gives you an integer.
You can always cast it back to a character, though: static_cast<char>(array[0]+1)
When adding two integral types, if they are different sizes then the smaller one gets converted to the larger one. The result of the addition has the larger type. For example char + int is an int. short + int is a long. int + long is a long.

There are some other details dealing with whether the types are signed or unsigned.
Topic archived. No new replies allowed.