我目前正在开发一个程序来解决背包问题,我不得不使用指向矩阵的指针。使用我在学校得到的伪代码后,我不断收到分段错误,根据 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("%dn", i);
K = K - wv[i];
}
}
return V[n][W];
}
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 数组,请先正确分配它。