我有一些 C++ 代码正在被一个 Assembly 模块调用。我的代码应该按指针对数组进行排序。
我的两个问题存在于第二个 for-loop
中:
- 我注释掉 cout,程序在接近我代码中的第二个
for-loop
时立即出现段错误,而不是第一个只输出数组的那个。我能够看到第一个for-loop
的输出。 - 我没有注释掉 cout 并且
for-loop
运行然后在必须递增i
时出现段错误。我能够看到此for-loop
产生的所有输出。
代码如下:
#include <iostream>
using namespace std;
extern "C" void swapASM(double (**address));
extern "C" void sortbypointers(double *arr[], long size)
{
cout << "Before sort: " << endl;
for(int i = 0; i < size; i++)
{
cout << (*(arr[i])) << " ";
}
// problems starts here
for(int i = 0; i < size; i++)
{
cout << endl << "i: " << i;
for(int j = i+1; i <= size; j++)
{
if((*(arr[i])) > (*(arr[j])))
{
//cout << endl << "Before swap: \ni: " << i << "\narr[i]: " << *(arr[i]) << "\nj: " << j << "\narr[j]: " << *(arr[j]) << endl;
swapASM(&(arr[i]));
//cout << endl << "After swap: \ni: " << i << "\narr[i]: " << *(arr[i]) << "\nj: " << j << "\narr[j]: " << *(arr[j]) << endl;
}
}
}
cout << endl << "After sort: " << endl;
for(int i = 0; i < size; i++)
{
cout << *(arr[i]) << " ";
}
cout << endl << "Return" << endl;
return;
}
最佳答案
int j = i+1; i <= size; j++;
我认为这是导致问题的原因。
关于c++ - 到达for循环时出现奇怪的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923221/