0

I knew that global int initalised array have default value 0, so I tried to see what default value a char array would have

char arr[10];
int main() {
  for(int i=0;i<10;++i)
    cout<<arr[i]<<endl;
  return 0;
}

using this code I found output as <0x00> 10 times each in new line in the light text, i.e NUL, as expected by me, in console of sublime text (printing in terminal just gave 10 blank lines)

But then I tried to write the output to a file using freopen("output.txt", "w", stdout); and to my surprise output changed to

000d 0a00 0d0a 000d 0a00 0d0a 000d 0a00
0d0a 000d 0a00 0d0a 000d 0a00 0d0a 

also on removing endl output was

0000 0000 0000 0000 0000 

further adding ' ' in place of endl gave 10 spaces only

I am unable to understand what's going on I expected zeros to be printed in all these cases, what's different in writing to a file to printing on terminal?

I looked up difference between NUL, NULL and 0 but still the output of these codes are not clear to me.

Can someone please help me to understand the reasoning? Thanks!

cheems
  • 164
  • 7
  • The `0x0d0a` pair is a carriage return and linefeed. You don't see the actual characters in the terminal but you do see the effect otherwise everything would be printed on a single line. – Retired Ninja Dec 09 '21 at 10:53
  • 1
    *I expected zeros to be printed in all these cases* And just why would you expect that? – Andrew Henle Dec 09 '21 at 10:54
  • @RetiredNinja Thanks, I think got first and second case, 00 is 8 bit representation of NUL, and 0d0a is for carriage return and linefeed, also is there any reason for space after word size other than reading clarity? Also, I still didn't get why only 10 spaces when replaced with ' ' why not 00 printed in that case? – cheems Dec 09 '21 at 11:16
  • That might just be your (hex) editor trying to show things nicely and can be turned off I guess. – Botje Dec 09 '21 at 12:12

0 Answers0