Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between int and char arrays?

Tags:

c++

What is the difference between int and char arrays below:

int main()
{
    int numbers[] = {2,1,3};
    char letter[] = {'a','b','\0'};
    cout<< numbers<<endl;
    cout<< letter<<endl;
}

Output:

0x22ff12 // an address
ab

Why isn't the 213 displayed ? I know the name of an array will point to the address of its first element, but why does a char array display different behavior?

like image 941
S.A.Parkhid Avatar asked Nov 25 '11 16:11

S.A.Parkhid


4 Answers

There is no operator<< overload that takes arrays, exactly, so the arguments you pass (eg numbers and letter) undergo array-to-pointer conversion, to void* and char* respectively.

There is an overload of operator<<() that takes a const void*, and another that takes a const char*. When you call:

cout<< numbers<<endl;

the const void* version is matched, but when you call:

cout<< letter<<endl;

the const char* version is matched.

In the const void* version, the pointer is displayed, while with the const char* version, the string is displayed up to the null terminator.

like image 88
John Dibling Avatar answered Oct 20 '22 21:10

John Dibling


When you print an array with cout it will print the base address of the array.

The exception is with char arrays which have been overloaded to print it as a c-string.

If you want to print the elements of the int array, you need to do it element-by-element.

like image 40
Mysticial Avatar answered Oct 20 '22 22:10

Mysticial


The reason is thatoperator<< overloaded for const char* which prints each character till it encounters \0.

There is no such overload corresponds to int[N] which prints each element in it. Instead when you write cout << numbers, it invokes operator<< which is overloaded for void*, and which prints the address.

However, if you overload operator<< for T[N], then you can print it like that as well.

Here is a simple illustration:

template<typename T, size_t N>
std::ostream & operator<<(std::ostream & out, const T (&a)[N])
{
   for(size_t i = 0 ; i < N ; ++i)
      out << a[i] << ' ';
   return out;
}

int main()
{
   int numbers[] = {2,1,3};
   char letter[] = {'a','b','\0'};
   cout<< numbers<<endl;
   cout<< letter<<endl;
}

Output:

2 1 3 
a b

Demo : http://ideone.com/O4T9N

like image 29
Nawaz Avatar answered Oct 20 '22 22:10

Nawaz


In C, and therefore in C++, a string is often represented by an array of chars terminated in a 0. Therefore an overloaded operator<< is provide for the class std::ostream, of which std::cout is an instance , which prints the char* as a string. There is no such common use of int arrays, nor any convention so the operator would 'know' how many elements to output, so the pointer to the array is matched to the version of operator<< which outputs any other pointer by printing its address.

like image 42
Pete Kirkham Avatar answered Oct 20 '22 20:10

Pete Kirkham