Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String arrays in C

Tags:

arrays

c

string

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

like image 472
0xFF Avatar asked Mar 02 '10 17:03

0xFF


2 Answers

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 '-'.

like image 157
Charles Beattie Avatar answered Nov 15 '22 21:11

Charles Beattie


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.

like image 27
Matthew Flaschen Avatar answered Nov 15 '22 19:11

Matthew Flaschen