Reputation: 4178
I have an array of strings which when I iterate through and print its elements gives me unexpected results.
char currencies[][3] = {"EUR", "GBP", "USD", "JPY", "CNY"};
void show_currencies()
{
int i;
for(i=0; i<5; i++)
{
printf("%s - ", currencies[i]);
}
}
when I call show_currencies()
I get this on output.
EURGBPUSDJPYCNY - GBPUSDJPYCNY - USDJPYCNY - JPYCNY - CNY -
Can anyone explain this behaviour.
Thank you
Upvotes: 11
Views: 461
Reputation: 5949
You are missing the nul terminators the strings are actually 4 characters long. Each string is then over writing the previous string's null terminator*. Try instead:
char currencies[][4] = {"EUR", "GBP", "USD", "JPY", "CNY"};
*As pointed out by caf it is not "over writing the previous string's null terminator" as the null terminator is never copied into the array. It is a fluke that the string is does not have garbled output after the final '-'.
Upvotes: 14
Reputation: 284786
You're declaring it wrong. This will work. It just lets the compiler set up an array of pointers-to-const-chars:
const char *currencies[] = {"EUR", "GBP", "USD", "JPY", "CNY"};
EDIT: Making it a two-dimension array, like Charles Beattie's answer, works too, provided you allocate space for the null. Also, specify that chars are const
, per Christoph.
Upvotes: 8
Reputation: 454922
Change
char currencies[][3]
to
char currencies[][4]
strings in C are NULL terminated, to make their handling (in printing, copying etc) easier.
example: char str[] = "ABC";
will declare a string of 4 char with \0
as the last char (index 3).
As a tip whenever on printing a char array you get unexpected results you might wanna check to see if the char array is NULL terminated or not.
Upvotes: 2
Reputation: 273169
You don't have an array of strings but an array of array-of-char. You could use:
char* currencies[] = {"EUR", "GBP", "USD", "JPY", "CNY"}; // untested
to allow for strings of different lengths.
Upvotes: 2
Reputation: 199195
My C is quite rusty, but try:
char currencies[][3] = {"EUR\0", "GBP\0", "USD\0", "JPY\0", "CNY\0"};
I'm just curious to know what happens
Upvotes: 0
Reputation: 57036
Sure. "EUR" is four characters long - three for the letters, one for the terminating null character. Since you're explicitly specifying three-character arrays, the compiler is truncating, and so your data is strung together. You're lucky there is apparently a zero character at the end of the array, or you could get all sorts of garbage. Change your declaration to char currencies[][4]
.
Upvotes: 0