Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializer-string for array of chars is too long C

Tags:

arrays

c

char

I'm working on a program that accepts input and and outputs a numerical value corresponding to the input. I get the error on the char part. I don't understand why it would have an error like that when there's only 27 characters in the array that has a size of 27?

int main ()
{
    char greek[27] = "ABGDE#ZYHIKLMNXOPQRSTUFC$W3";
}
like image 471
odelentok Avatar asked Aug 22 '14 08:08

odelentok


Video Answer


1 Answers

You need one more [28] for the trailing '\0' to be a valid string.

Take a look to C Programming Notes: Chapter 8: Strings:

Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character with the value 0. (The null character has no relation except in name to the null pointer. In the ASCII character set, the null character is named NUL.) The null or string-terminating character is represented by another character escape sequence, \0.

And as pointed out by Jim Balter and Jayesh, when you provide initial values, you can omit the array size (the compiler uses the number of initializers as the array size).

char greek[] = "ABGDE#ZYHIKLMNXOPQRSTUFC$W3";
like image 97
David Ranieri Avatar answered Sep 28 '22 20:09

David Ranieri