Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - char array and the null character

I have two questions about char array.

  1. from the code bellow, since arr is const, why doesn't the compiler give me an error since I'm rewriting it?

    char arr[5]; // arr is a const pointer to (*)[5] array
    cin>>arr; //   
    
  2. when I initialized a char array like this:

    char arr[5]={'h','i'};
    

    if I did this:

    cout << arr << "something here \n"; 
    

    it will print hisomething here. I thought It should print out

    hi   something here
    

    with 3 witespaces.

    But if I did this:

    for(int i = 0; i < 5; i++){
      cout << arr[i];
    }
    

    it will printout the 3 whitespaces.

The second case seems to prove that the compiler doesn't add any null characters. So how can the compiler ignore the 3 whitespaces?

like image 678
AlexDan Avatar asked Aug 05 '26 01:08

AlexDan


1 Answers

  1. This array is not const, because there is no const qualifier.
  2. If you don't specify remaining values in initializer list, they will be initialized to 0. 0 is used to terminate C strings, not as a whitespace.

As for your claim, that for(int i=0;i<5;i++){ cout << arr[i]; } printed whitespace - how did you checked that?

For me:

#include <iostream>

int main(){
    char arr[5]={'h','i'};
    for(int i=0;i<5;i++){ std::cout << arr[i]; }
    std::cout << "X" << std::endl;
}

prints:

hiX

and hexdumped:

$ ./t | hexdump -Cv
00000000  68 69 00 00 00 58 0a                              |hi...X.|
00000007

There are '\0' chars printed. Their display seems to be operating system dependent. But they are not a whitespace.

like image 124
Rafał Rawicki Avatar answered Aug 06 '26 14:08

Rafał Rawicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!