简体   繁体   中英

C : Pass Array of string as function argument

So what I have is a file main.c which is including a header file I made utils.h , containing forward references to functions in my source file utils.c

In utils.c:

I have a function that accepts an array of string as an argument, and prints it out as a menu:

void showMenu(const char *menu[])
{
    int menulen = sizeof(menu)/sizeof(*menu);

    int i;
    for(i = 0; i < menulen; i++)
    {
        printf("[%d] .. %s\n", (i+1), menu[i]);
    }
}

In main.c:

I simply call this function:

const char *menu[] =
{
        "Customers",
        "Orders",
        "Products"
};

int main(void)
{
    showTitle("Customer Orders System");
    int menulen = sizeof(menu)/sizeof(*menu);
    showMenu(menu);
    getch();
}

My Problem:

My showMenu function is calculating the length of the array, and then iterating through it, printing the strings. This used to work when the function was in main.c , but I am required to organize this project in separate files.

The length is now being calculated as 1. After doing some debugging, I think this is a pointer-related problem, but I seem to resolve it. The argument for showMenu after the call is of type

const char** menu

having only the first element of my original array.

I tried deferencing the argument, passing it a pointer of the array, and both at the same time.
Strangely enough, the same line of code works in the main function. I really don't want to have to resolve this problem by adding a length of array argument to the function.

Any help is greatly appreciated.

This is because arrays decay into pointers to their first element when passed to a function like yours, and there is no information retained about the number of elements. In the scope where the array is declared, this decay hasn't happened, so sizeof works.

You must either add length of array as an extra argument, or make sure the array is terminated by an appropriate sentinel value. One popular such value is NULL , ie you make sure the last valid index holds a string pointer whose value is NULL , which then indicates "no more data, stop":

const char *menu[] =
{
    "Customers",
    "Orders",
    "Products",
    NULL /* This is a sentinel, to mark the end of the array. */
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM