简体   繁体   English

C:将字符串数组作为函数参数传递

[英]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 所以我所拥有的是一个文件main.c ,它包含一个我创建的utils.h头文件,包含我的源文件utils.c中函数的前向引用。

In utils.c: 在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: 在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. 我的showMenu函数正在计算数组的长度,然后迭代它,打印字符串。 This used to work when the function was in main.c , but I am required to organize this project in separate files. 当函数在main.c中时 ,这曾经工作,但是我需要在单独的文件中组织这个项目。

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. 现在长度计算为1.在做了一些调试后,我认为这是一个与指针相关的问题,但我似乎解决了它。 The argument for showMenu after the call is of type 调用后showMenu的参数是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. 奇怪的是,同一行代码在main函数中起作用。 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. 在声明数组的范围内,此衰减尚未发生,因此sizeof有效。

You must either add length of array as an extra argument, or make sure the array is terminated by an appropriate sentinel value. 您必须添加数组长度作为额外参数,或者确保数组以适当的sentinel值终止。 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": 一个流行的此类值为NULL ,即您确保最后一个有效索引包含一个字符串指针,其值为NULL ,然后指示“不再有数据,停止”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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