Reputation: 57
I wrote this knapsack problem solution in c++ however when I run it, it gives me segmentation fault I have tried everything and my compiler will always give me the segmentation fault error.
#include<iostream>
#include<algorithm>
int knapsack(int v[],int w[],int n,int W)
{
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
for(int i = 0; i <= n; i++){
for(int j = 1; j<=W; j++)
{
if(w[i]<=W)
{
V[i][j] = std::max(V[i-1][j], v[i]+V[i-1][j-w[i]]);
}
else
{
V[i][j] = V[i-1][j];
}
}
}
return V[n][W];
}
int main()
{
int v[4] = {10,40,30,50};
int w[4] = {5,4,6,3};
int n = 3;
int W = 10;
std::cout<<"item value:"<<knapsack(v,w,n,W);
}
Upvotes: 1
Views: 209
Reputation: 11350
Array indices go from 0 to length-1. in you loop
for(int i = 0; i<=W;i++)
i
can reach W
, then V[0][W]
is out of bounds which causes the seg fault. You have to use <
instead of <=
:
for(int i = 0; i < W; i++)
n
should probably be 4, if it's meant to represent the size of the array, a std::vector
would make your life easier here, because a vector knows it's size
Upvotes: 2
Reputation: 5566
int V[n][W];
for(int i = 0; i<=W;i++)
{
V[0][i] = 0;
}
Note that V's indexes go from V[0][0]
to V[0][W-1]
. Your for loop will try to read V[0][W]
.
The same error is repeated in other places. Your end condition in your for loops should be <
(strictly less) instead of <=
(less or equal than).
Upvotes: 1