[英]Why does this code return segmentation fault error?
I'm writing this code to optimize the time of the problem and it is a dp problem我写这段代码是为了优化问题的时间,这是一个dp问题
Given string S is: 574674546476
给定字符串 S 是:
574674546476
for index 1: Number of even numbers from 5 to end of the string is 7 so the result of index 1 is 7.对于索引 1:从 5 到字符串末尾的偶数个数为 7,因此索引 1 的结果为 7。
for index 2: Number of even numbers from 7 to end of the string is 7 so the result of index 2 is 7.对于索引 2:从 7 到字符串末尾的偶数个数为 7,因此索引 2 的结果为 7。
for index 3: Number of even numbers from 4 to end of the string is 7 so the result of index 3 is 7.对于索引 3:从 4 到字符串末尾的偶数个数为 7,因此索引 3 的结果为 7。
for index 3: Number of even numbers from 6 to end of the string is 6 so the result of index 4 is 6.对于索引 3:从 6 到字符串末尾的偶数个数为 6,因此索引 4 的结果为 6。
... ...
This is the code which I've tried but it shows segmentation fault in this code这是我尝试过的代码,但它在这段代码中显示了分段错误
#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[10005];
int i;
cin >> str;
int n = strlen(str);
int arr[10005];
for (i = 0; i < n; i++) {
arr[i + 1] = str[i] - 48;
}
int tab[n + 1];
if (arr[n] % 2 == 0) {
tab[n] = 1;
}
else {
tab[n] = 0;
}
for (i = n - 1; i >= 1; i++) {
if (arr[i] % 2 == 0) {
tab[i] = tab[i + 1] + 1;
}
else {
tab[i] = tab[i + 1];
}
}
for (i = 1; i <= n; i++) {
cout << tab[i] << " ";
}
}
I expect output should be我希望输出应该是
7 7 7 6 5 5 4 4 3 2 1 1
7 7 7 6 5 5 4 4 3 2 1 1
But when I'm giving input 574674546476
and I want to solve using dp I write the code, it shows segmentation fault.但是当我提供输入
574674546476
并且我想使用 dp 解决我编写代码时,它显示分段错误。
for(i=n-1;i>=1;i++){
should be应该
for(i=n-1;i>=1;i--){
That explains the crash but you also have the two common errors we see when people submit competitive code这解释了崩溃,但是当人们提交有竞争力的代码时,我们也会看到两个常见错误
This is not a standard C++ header file这不是标准的 C++ 头文件
#include<bits/stdc++.h>
In this code you should be using在此代码中,您应该使用
#include <iostream>
And this is not legal C++这不是合法的 C++
int tab[n+1];
since in C++ array sizes must be compile time constants , but here n
is a variable.因为在 C++ 中数组大小必须是编译时常量,但这里
n
是一个变量。 You should use你应该使用
#include <vector>
and和
vector<int> tab(n+1);
instead.反而。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.