我目前正在研究解决背包问题的程序,我不得不使用指向矩阵的指针。在使用伪代码后我在学校给出了我一直收到分段错误,根据valgrind,这就是原因:
1 errors in context 1 of 2:
==10545== Invalid write of size 4
==10545== at 0x4009C3: DP (dp.c:70)
==10545== by 0x400914: main (dp.c:39)
==10545== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==10545==
==10545==
=
=10545== 1 errors in context 2 of 2:
==10545== Use of uninitialised value of size 8
==10545== at 0x4009C3: DP (dp.c:70)
==10545== by 0x400914: main (dp.c:39)
==10545==
我试图用过去的答案解决问题,但我似乎无法弄明白。在学校的其他人做了完全相同的事情,他们似乎没有收到这个问题。在代码中我似乎没有看到或意识到的任何错误?
int **V, **keep; // 2d arrays for use in the dynamic programming solution
// keep[][] and V[][] are both of size (n+1)*(W+1)
int i, w, K;
// Dynamically allocate memory for variables V and keep
V = (int**)malloc((n+1) * (W+1) * sizeof(int*));
keep = (int**)malloc((n+1) * (W+1) * sizeof(int*));
// set the values of the zeroth row of the partial solutions table to zero
for (w = 0; w <= W; w++)
{
V[0][w] = 0;
}
// main dynamic programming loops , adding one item at a time and looping through weights from 0 to W
for (i = 1; i <= n; i++)
for (w = 0; w <= W; w++)
if ((wv[i] <= w) && (v[i] + V[i-1][w - wv[i]] > V[i - 1][w]))
{
V[i][w] = v[i] + V[i-1][w-wv[i]];
keep[i][w] = 1;
}
else
{
V[i][w] = V[i-1][w];
keep[i][w] = 0;
}
K = W;
for (i = n; i >= 1; i--);
{
if (keep[i][K] == 1)
{
printf("%d\n", i);
K = K - wv[i];
}
}
return V[n][W];
}
答案 0 :(得分:1)
V = (int**)malloc((n+1) * (W+1) * sizeof(int*));
...
for (w = 0; w <= W; w++)
{
V[0][w] = 0;
}
malloc
来电中提供的尺寸没有任何意义。并且您从未初始化V[0]
(或任何V[i]
。它包含垃圾值。但您尝试访问V[0][w]
(以及V[i][w]
之后)。这是未定义的行为。
如果您打算将V
用作2D数组,请先allocate it properly。