Search code examples
arraysccharc-stringsfunction-definition

Indexing from a list of strings in C?


Obvious newbie question, I'm trying trying to write something that you put in an int and it gives you the month. Here is a function python version:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def get_month(mon):
    return months[mon]

In C, I have done this:


#include <stdio.h>
char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};


int main()
{
char get_month(int m)
{
    return *months[m];
}
        
for (int i = 0; i < 12; i++)
{
    char    this_month = get_month(i);
    printf ("Month %d is %c\n", i, this_month);
}

return 0;
}

I get this output

Month 1 is J
Month 2 is F
Month 3 is M
Month 4 is A
Month 5 is M
Month 6 is J
Month 7 is J
Month 8 is A
Month 9 is S
Month 10 is O
Month 11 is N
Month 12 is D

I think I have to somehow account for the length of the strings (or are they technically chars?) in *months[12] but I don't know how. If I change it to *months[12][3] I get

warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]

Also, what if they were not all the same length (i.e. the months were written out fully)?


Solution

  • Defining a function within another function is not a standard C feature.

    You need to move the definition of the function get_month above main.

    Elements of the array monhts have the type char *.

    char *months[12] = { /*... */ };
    

    So the function get_month that returns element of the array must have the same return type as the type of the array elements.

    char * get_month(int m)
    {
        return months[m];
    }
    

    So within the for loop in main you need to write

    char   *this_month = get_month(i);
    printf ("Month %d is %s\n", i, this_month);
    

    As for this expression *months[m] then it yields the first character of the string pointed to by the pointer months[m] because you have an array pf pointers.