5

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";
}
2
  • 5
    use char greek[] = "ABGDE#ZYHIKLMNXOPQRSTUFC$W3"; Commented Aug 22, 2014 at 8:35
  • Related: stackoverflow.com/q/1697965/694576 Commented Aug 22, 2014 at 8:41

1 Answer 1

10

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";
Sign up to request clarification or add additional context in comments.

4 Comments

It's far better to use char greek[] than char greek[28].
@JimBalter May I ask why?
@JimBalter I'd expect you to explain some more about how the compiler deals with the "empty space" between square brackets. I know not mentionning the length of the array like that is done some times, however unless you dynamically allocate memory, as far as I know, the compiler always needs to know in advance the length of the array in order to reserve the necessary space on the stack. So once more I hoped you would have explained a little more about the "[<nothing>]". I.e. how that works behind the scenes. Why wasn't that incredibly obvious?
@trilolil You are answering yourself: the compiler always needs to know in advance the length of the array in order to reserve the necessary space on the stack, but manually counting is prone to failures; e.g. char name[6] = "Ramón"; doesn't leave space for the trailing NUL due to ó consuming 2 bytes, so let the compiler count for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.