为什么这个字符串数组将错误的元素传递给这个函数?

Why this array of strings pass the wrong elemet to this function?

这是我的代码的一部分:

typedef struct drink{
    char name[32];
    int price;
    struct drink* next;
}drink;

typedef struct pub{
    char name[32];
    drink* price_list;
    struct pub* next;
}pub;

pub *find_cheapest(pub *p, char **italok, int n)
{
   .
   .
   .
}

我想将 *italok[] 数组传递给 find_cheapest() 函数,但它无法获取正确的元素: 非常感谢您的帮助,谢谢。

char *italok[] = {"Gosser", "Soproni"};
printf("\n%s\n", find_cheapest(p, italok, 2));

char *italok[] = {"Gosser", "Soproni"};

在这里,您声明了一个 auto 变量 *italok[]Auto 变量生命周期从程序执行进入函数或语句块时开始,到执行离开块时结束。因此,*italok[] 的内容在 find_cheapest 函数中不再可用。

有两种保存方式:

  1. 静态内存分配:使用static variables

static variable的生命周期等于程序的生命周期。因此,它的值也保留在其他功能块中。 Change the auto variable to static.
static char *italok[] = {"Gosser", "Soproni"};

  1. 动态内存分配:使用malloc()

动态对象的生命周期从为对象分配内存(例如,通过调用 malloc())开始,到内存被释放时结束。 malloc 变量的值保留在其他函数中。因此,使用 malloc.

将内存分配给 italok[]
char **italok = malloc(10 * sizeof(char *));

     for (int i = 0; i < 10; i++)
     {
         italok[i] = malloc(20 * sizeof(char));
     }
italok[0] = "Gosser";
italok[1] = "Soproni";

同样,将p声明为静态或动态变量。