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
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 '-'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With