I read that when one inicializes an array it is possitle to use a string literal.
But if the list if inicializers is bigger than the size of array, an error is caught.
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char cAr2[3] = "ABC";
for (int i = 0; i < 3; i++)
cout<<cAr2[i]<<endl;
system("pause");
return 0;
}
Well, this example is given in my book.
It really ends like this: error C2117: ‘cAr2’ : array bounds overflow.
Could you tell me what is what here: I can see an array of 3 elements and 3 elements being placed into it. Everything seems Ok. Why error?
The string literal
"ABC"gives you an “array of 4const char“. There are 4 characters because the string is terminated with the null character. That is, your initialisation would be equivalent to:The null character is implicitly appended to the end of your string so that algorithms that loop over the contents of the array know when to stop without having a string length explicitly given.