Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior of character and integer array in c++

Tags:

c++

arrays

Here is a small code in c++ where I am creating two arrays of char and int data types respectively.However the same print operation is behaving differently for both the arrays

#include<iostream>
using namespace std;
int main()
{
    char a[5]={'h','e','l','l','o'};
    int b[5]={1,2,3,4,5};

    cout<<a;                       //displays the string "hello"
    cout<<"\n"<<b;                 //displays the address of b[0]
    return(0);
}

I expected the output to be the address of the first element of both the arrays i.e. address of a[0] and b[0] respectively however char type array is behaving differently in this case.

like image 969
yash gandhi Avatar asked Mar 03 '23 22:03

yash gandhi


1 Answers

It's a special overload of operator << for cout that treats char * arguments as null terminated strings and prints the entire string.

If you want to print the address cast it to void *.

cout << (void *) a;
like image 72
frogatto Avatar answered Mar 10 '23 18:03

frogatto