0

If  I have array string for courses name like
courseName = {"java","math","physics"}

and enum have constant variables with code for courses like
CSC = 320

How to associate them in C language ?

IrAM
  • 1,720
  • 5
  • 18
Bn.
  • 27
  • 5

2 Answers2

2

You need some way to map the enumeration to the array index.

A simple array of structures with a "from" and "to" member solve it:

struct
{
    int course;     // Course enumeration value
    unsigned name;  // Name array index
} course_to_name_map[] = {
    { JAVA_101, 0 },
    // etc...
};

To find the name loop over the mapping array to find the course, and then use the corresponding index to get the name:

char *get_course_name(int course)
{
    static const size_t map_element_count = sizeof course_to_name_map / sizeof course_to_name_map[0];

    for (unsigned i = 0; i < map_element_count; ++i)
    {
        if (course_to_name_map[i].course == course)
        {
            return course_names[course_to_name_map[i].name];
        }
    }

    // Course was not found
    return NULL;
}

Note that this is only one possible solution. It's simple but not very effective.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

why not:

enum KEY {
  KEY_JAVA = 320,
  KEY_MATH = 123,
  KEY_PHYSICS = 17,
};

char *course_to_name[] = {
  [KEY_JAVA] = "java",
  [KEY_MATH] = "math",
  {KEY_PHYSIC] = "physics",
};

// usage:
course_to_name[KEY_JAVA];

It works quite well as long as courses codes are relatively small.

tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • Well, in this case `KEY_JAVA = 320` , so `char *course_to_name[] = { [KEY_JAVA] =` creates an array of 320 elements. Looks like a huge waste of space. – KamilCuk Mar 16 '21 at 09:16
  • @KamilCuk, it depends how tight are the keys distributed. For a values up to a few thousands this solution is OK. – tstanisl Mar 16 '21 at 09:19
  • "few thousands"! Well, no, sorry, this is just a waste of space and wouldn't make pass my code review. Assuming `char*` is 4 bytes, this array has 3 values - that's 1.2 kilobytes wasted (assuming you make the array `const char *const`) of ROM just for pointers. On a STM32F103C8T6 with 64kB that's ~2% of flash wasted just for one array. Values up to maybe 10s may be acceptable, but I would go with a map anyway. – KamilCuk Mar 16 '21 at 09:27