我正在使用c和动态内存,但是在显示int **数组中的某些值时遇到了问题
我用Valgrind看问题出在哪里,我知道在哪里,但是我真的不知道如何解决它,因为问题对我来说毫无意义。
result_s ** greedy(case_s ** cases, int cases_quantity)
{
int ** case_conteiners;
int * current_conteirners;
result_s ** results = malloc(sizeof(result_s*)*cases_quantity);
for (int i = 0; i < cases_quantity; ++i)
{
results[i] = malloc(sizeof(result_s));
int conteiners_quantity = cases[i]->conteiners_quantity;
int fuel = cases[i]->fuel;
int current_fuel = 0;
int max_conteiner = 0;
int current_count = 0;
int case_count = 0;
current_conteirners = malloc(sizeof(int)*2);
case_conteiners = malloc(sizeof(int*)*256);
for (int j = 0; j <= conteiners_quantity+1; ++j)
{
if (current_fuel < fuel)
{
max_conteiner = max_value(cases[i]->conteiners, cases[i]->conteiners_quantity);
printCurrent(i,max_conteiner);
current_conteirners[current_count] = max_conteiner;
current_fuel += max_conteiner;
current_count++;
}
else if (current_fuel >= fuel && current_count <= 2 )
{
case_conteiners[case_count] = current_conteirners;
printf("\n\n HERE IS THE LEAK %d\n\n", case_conteiners[0][1]);
printf("\n\n HERE IS OK %d\n\n", current_conteirners[1]);
current_conteirners = malloc(sizeof(int)*20);
if (j != conteiners_quantity && i-1 != cases_quantity)
{
current_fuel = 0;
current_count = 0;
}
case_count++;
}
}
if (current_fuel >= fuel && current_count <= 2 )
{
case_conteiners[case_count] = current_conteirners;
case_count++;
}
results[i]->conteiners = case_conteiners;
results[i]->conteiners_quantity = 2;
results[i]->case_count = case_count;
}
return results;
}
如您所见,我想创建一个数组数组。我想将许多“ current_conteiners”放入“ case_conteiners”中。
几乎所有东西都可以正常工作,但是case_conteiners [0] [1]仅给我一个内存号,而case_conteiners [1]给我正确的值。
编辑:这是我称之为贪婪函数的地方。案例是一系列案例。具有2个int和一个数组int的Struct。
results = greedy(cases, atoi(data[1]));