This is part of my code:
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)
{
.
.
.
}
I would like to pass the *italok[]
array to the find_cheapest()
function but it fails to get the correct elements:
I would appreciate the help, thank you.
char *italok[] = {"Gosser", "Soproni"};
printf("\n%s\n", find_cheapest(p, italok, 2));
char *italok[] = {"Gosser", "Soproni"};
Here, you are declaring an auto
variable *italok[]
. Auto
variable lifetime begins when program execution enters the function or statement block and ends when execution leaves the block. So, the contents of *italok[]
are no longer available in find_cheapest
function.
There are two ways to sove it:
static variables
The lifetime of static variable
is equal to the lifetime of the program. Hence, its values are retained inside other function blocks also. Change the auto variable to static
.
static char *italok[] = {"Gosser", "Soproni"};
malloc()
The lifetime of a dynamic object begins when memory is allocated for the object (e.g., by a call to malloc()
) and ends when memory is deallocated. The values of the malloc
'ed variables are retained inside other functions. So, allocate memory to italok[]
using malloc
.
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";
Similarly, declare p
as a static or dynamic variable .