Click to See Complete Forum and Search --> : excess elements in char array initializer


JesterDev
02-23-2004, 08:48 PM
I'm working out of a book on c and trying to set some values for an array:



char letter_grade[] = { "A", "B", "C", "D", "F" };



This is how it shows to do it earlier in the book. But when I try to compile I get this error:

excess elements in char array initializer

What am I doing wrong? I remember reading that the first value is set to null, maybe I'm wrong.. Could this be the case?

tecknophreak
02-23-2004, 08:53 PM
Originally posted by JesterDev
I'm working out of a book on c and trying to set some values for an array:



char letter_grade[] = { "A", "B", "C", "D", "F" };




the double quotes tell the compiler that it is a char string, so what you're telling the compiler is that you want to stick 5 char strings into 1 char array.

fix: use single quotes, i.e.

char letter_grade[] = { 'A', 'B', 'C', 'D', 'F' };

bandwidth_pig
02-23-2004, 08:57 PM
You don't need to declare the number of elements within the array then? I'm new at this also.

char letter_grade[5]

I have only worked with real basic arrays, and haven't come across this syntax, although it actually seems like a more efficient way to get the job done.

maccorin
02-23-2004, 09:21 PM
you don't need the size of the array in there IF you have an initializer { ... } because the compiler simply counts the number of elements in the initializer. It's still a static size though.

if you want a dynamic size, in C++ you can use std::vector, and in C you'll have to roll your own, w/ malloc/realloc/free

JesterDev
02-23-2004, 10:06 PM
Originally posted by tecknophreak
the double quotes tell the compiler that it is a char string, so what you're telling the compiler is that you want to stick 5 char strings into 1 char array.

fix: use single quotes, i.e.

char letter_grade[] = { 'A', 'B', 'C', 'D', 'F' };

Thanks for that. This is one of the things while reading I said I'd never do. I'm sure there will be more encounters such as this. :)