使用 std::fill 时出现分段错误
Segmentation fault when using std::fill
我正在尝试 运行 以下代码,但它给我分段错误 :-
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
int dp[MAX][MAX];
string s1, s2;
int lcs(int i, int j)
{
int val;
if ( i < 0 || j < 0)
return 0;
else if (dp[i][j] != -1)
{
return dp[i][j];
}
else
{
val = max(lcs(i-1,j), lcs(i, j-1));
if ( s1[i] == s2[j])
val = max(lcs(i-1,j-1) + 1, val);
}
dp[i][j] = val;
return val;
}
int main()
{
int tc;
scanf("%d", &tc);
while (tc--)
{
fill(&dp[0][0], &dp[MAX][MAX], 0);
cin>>s1;
cin>>s2;
printf("LCS = %d\n", lcs(s1.size()-1, s2.size()-1));
}
return (0);
}
现在,它在 while 循环的 printf
行给我一个分段错误。但是,如果我把fill语句注释掉,那么就没有分段错误了。
这可能是什么原因?
&dp[MAX][MAX]
这引用了尾后数组的尾后指针。你想要最后一个数组的结束指针,而不是:
&dp[MAX-1][MAX]
否则它将遍历尾部数组,导致段错误。
我正在尝试 运行 以下代码,但它给我分段错误 :-
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
int dp[MAX][MAX];
string s1, s2;
int lcs(int i, int j)
{
int val;
if ( i < 0 || j < 0)
return 0;
else if (dp[i][j] != -1)
{
return dp[i][j];
}
else
{
val = max(lcs(i-1,j), lcs(i, j-1));
if ( s1[i] == s2[j])
val = max(lcs(i-1,j-1) + 1, val);
}
dp[i][j] = val;
return val;
}
int main()
{
int tc;
scanf("%d", &tc);
while (tc--)
{
fill(&dp[0][0], &dp[MAX][MAX], 0);
cin>>s1;
cin>>s2;
printf("LCS = %d\n", lcs(s1.size()-1, s2.size()-1));
}
return (0);
}
现在,它在 while 循环的 printf
行给我一个分段错误。但是,如果我把fill语句注释掉,那么就没有分段错误了。
这可能是什么原因?
&dp[MAX][MAX]
这引用了尾后数组的尾后指针。你想要最后一个数组的结束指针,而不是:
&dp[MAX-1][MAX]
否则它将遍历尾部数组,导致段错误。