Pepperwork
Pepperwork

Reputation: 105

C++ sized char array initialized by setting to string literal causes array bounds overflow

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?

Upvotes: 0

Views: 1160

Answers (4)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

The string literal "ABC" gives you an "array of 4 const char". There are 4 characters because the string is terminated with the null character. That is, your initialisation would be equivalent to:

char cAr2[] = {'A', 'B', 'C', '\0'};

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.

Upvotes: 3

Kevin Tran
Kevin Tran

Reputation: 80

If you want to initialize using a string literal I think you'll want to do something like this:

char *cAr2 = "ABC";

However, if you'd like to keep the same type do this:

char cAr2[3] = { 'A', 'B', 'C' };

Upvotes: -2

RonaldBarzell
RonaldBarzell

Reputation: 3830

Well, the easy answer is this: if you're going to use an initializer, save yourself some grief and leave out the size.

The longer answer is that strings are null-terminated, which means there's an additional character you do not see at the end of the string. So you will need an array of size n+1 where n is the number of characters you see.

Upvotes: 3

A B
A B

Reputation: 4148

The size 3 is not large enough for the "ABC" string:

 char cAr2[3] = "ABC"; 

You need at least 4 characters to store this string with the null terminator

Even if your compiler auto corrects that (I am not sure), it is not a good idea to undersize the array..

Upvotes: 1

Related Questions