0

I am working on Xcode 14.0.1, and the following output doesn't make sense to me for the following code. How can I fix this?

int main()
{
    const char arr1[6] = {'1','2','3','4','5','6'};
    const char arr2[1] = {'2'};
    cout << arr2 << endl;
    return 0;
}

The following code outputs

2123456
Program ended with exit code: 0

Can someone please explain what is going on here?

I was expecting the output code to be

2
Program ended with exit code: 0
  • 1
    The array is not null terminated so `cout << arr2;` is **undefined behavior**. – Jason Oct 31 '22 at 05:06
  • 1
    *"How can I fix this?..."* Add a null character `'\0'` at the end of each of the array. Also refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which are also available as PDFs for free. – Jason Oct 31 '22 at 05:08
  • Your code has undefined behaviour since `arr2` does not have a terminating nul character (which has numeric value zero). If you want to print arrays of `char` without undefined behaviour, ensure a nul terminator is present in each array. Your specific output probably occurs because (1) your compiler has placed `arr2` in memory immediately before `arr1` AND (2) a byte with zero value exists in memory immediately after the end of `arr1`. Neither (1) nor (2) are guaranteed so you should not rely on them always occurring. – Peter Oct 31 '22 at 05:14

0 Answers0