I have two questions about char array.
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; //
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?
const, because there is no const qualifier.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With