-1
我目前工作的一个程序来解决背包问题,我不得不使用指针的矩阵。我在学校被赋予使用伪后,我不断收到分段错误,并根据Valgrind的就是这个道理:地址0x0不stack'd,malloc分配或(最近)free'd
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];
}
NULL指针解除引用。 –