NinjaCowgirl
NinjaCowgirl

Reputation: 2561

Char array allocation

In C++, if I do:

char myArray[] = {'1','2','3','4','5','6','7','8','9'}; 

Does that allocate 10 spaces? The last element being '/0'?

What about:

char myArray[9] = {'1','2','3','4','5','6','7','8','9'}; 

Did I allocate only 9 spaces in this case? Is this bad?

And, finally, what happens when I do:

char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'}; 

Upvotes: 1

Views: 361

Answers (4)

Luchian Grigore
Luchian Grigore

Reputation: 258568

char arrays don't behave differently than any other arrays when you use list-initialization. Would you expect

int x[] = {1,2};

to magically append a 0 as the last element and make x have 3 elements?

In case you provide fewer elements, then the last ones are value-initialized, so

char myArray[10] = {'1','2','3','4','5','6','7','8','9'}; 

would be null-terminated, but

char myArray[9] = {'1','2','3','4','5','6','7','8','9'}; 

isn't.

Upvotes: 1

timrau
timrau

Reputation: 23058

char myArray[] = {'1','2','3','4','5','6','7','8','9'}; 

This only allocates 9 elements.

char myArray[9] = {'1','2','3','4','5','6','7','8','9'}; 

Yes, this line also allocates 9 elements.

char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'}; 

The last one should be '\0' instead of '/0'.

What you are thinking about should be

char myArray[] = "123456789";

which allocates 10 characters (1 for the trailing '\0' at the end of the string literal)

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

No, you'll only get the trailing NUL when using a string literal, i.e.:

// Array of 10 bytes
char myArray[] = "123456789";

// same as:
char myArray[] = {'1','2','3','4','5','6','7','8','9','\0'}; 

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

char myArray[] = {'1','2','3','4','5','6','7','8','9'}; 

Does that allocate 10 spaces? The last element being '/0'?

No. 9.


char myArray[9] = {'1','2','3','4','5','6','7','8','9'}; 

Did I allocate only 9 spaces in this case?

Yes.

Is this bad?

No.


and finally what happens when I do

char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'}; 

Assuming you meant '\0', exactly what it looks like.

There's no magic in any of these cases — you get precisely what you're asking for.

Automatic null-termination is something that comes into play with string literals:

char myArray1[10] = "123456789";
char myArray2[9]  = "123456789";  // won't compile - wrong size
char myArray3[]   = "123456789";  // still 10 elements - includes null terminator

Upvotes: 9

Related Questions