Search code examples
cpointersmultidimensional-arrayimplicit-conversionfunction-declaration

strcpy through array of strings passed to a function?


Long story short, I'm making this 3D OpenGL builder game. The details don't matter much, but here is my problem. I have this array of strings:

char building_category_names_UPPER_CASE[][30] = { "NOTHING", "WAREHOUSE", "PROCESSING PLANT", "FACTORY", "OFFICE" }; 

And I'm trying to pass them to a function that accepts a "list" in the form of an array of strings and creates buttons via the Create_Button method for each item in that list.

void Create_Button_List(char** list, int list_size, char* group_name, int pos_x, int pos_y)
{
    for (int i = 1; i < list_size; i++)
    {
        char name[50];
        strcpy(name, list[i]);

        char group[50];
        strcpy(group, group_name);

        Create_Button(name, group, pos_x, i * pos_y, 205, 50, text_color_white, bg_color, text_color_white, bg_color_hover);
    }
} 

But even though VS doesn't give me any errors when building, I still get an access violation error when it reachs the strcpy(name, list[i]); part.

Image of the error

What is the problem here? Is this not how I'm supposed to pass the two dimensional char array? Or is the problem with how I'm passing it to strcpy? Just to be clear, list_size is 5 in this case, so that's correct, the problem shouldn't be with the for cycle going out of bounds.

If anyone can help me with this, thanks in advance!


Solution

  • This array

    char building_category_names_UPPER_CASE[][30] = { "NOTHING", "WAREHOUSE", "PROCESSING PLANT", "FACTORY", "OFFICE" }; 
    

    used in expressions like for example a function argument is implicitly converted to pointer to its first element.

    The element type of the array is char[30]. So the function that accepts this array as an argument needs to declare the corresponding parameter as

    char ( *list )[30]
    

    There is no implicit conversion between the pointer types char ( * )[30] and char **.

    So change the type of the first function parameter.

    Another approach is just to change the declaration of the array like

    char * building_category_names_UPPER_CASE[] = { "NOTHING", "WAREHOUSE", "PROCESSING PLANT", "FACTORY", "OFFICE" }; 
    

    In this case the function parameter may indeed have the type char **.