sho*_*ory -2 c++ segmentation-fault
码:
#include <iostream>
using namespace std;
void mix(int *a, int *b, int *c, int m, int n)
{
int i, j = 0;
for(i = 0; i < m; i++)
{
if(a[i] % 2 == 0)
{
c[j] = a[i];
j++;
}
}
for(i = m - 1; i >= 0; i++)
{
if(a[i] % 2 == 1)
{
c[j] = a[i];
j++;
}
}
for(i = 0; i < n; i++)
{
if(b[i] % 2 == 0)
{
c[j] = b[i];
j++;
}
}
for(i = n - 1; i >= 0; i++)
{
if(b[i] % 2 == 1)
{
c[j] = b[i];
j++;
}
}
cout << j << ' ';
}
int main()
{
int a[10], b[10], c[20], m, n;
cout << "m: ";
cin >> m;
cout << "\nn: ";
cin >> n;
int i;
for(i = 0; i < m; i++)
{
cin >> a[i];
}
for(i = 0; i < n; i++)
{
cin >> b[i];
}
mix(a, b, c, m, n);
for(i = 0; i < (m+n); i++)
{
cout << c[i];
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我检查并重新检查了我的数组的大小,我无法弄清楚为什么代码在mix(...)函数中产生段错误.这可能是使用-O2优化的问题吗?此外,我已确保指数匹配.我认为问题在于c[j] = a[i],但我不明白为什么会导致这种分段错误.
对于这两个循环你正在做i++而不是i--
for(i = m - 1; i >= 0; i--)
{
if(a[i] % 2 == 1)
{
c[j] = a[i];
j++;
}
}
for(i = n - 1; i >= 0; i--)
{
if(b[i] % 2 == 1)
{
c[j] = b[i];
j++;
}
}
Run Code Online (Sandbox Code Playgroud)