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:
*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 ‘-‘.