【发布时间】:2014-11-14 05:00:10
【问题描述】:
我有一些被汇编模块调用的 C++ 代码。我的代码应该按指针对数组进行排序。
我的两个问题在于第二个for-loop:
- 我注释掉 couts 并且程序在接近我的代码中的第二个
for-loop时立即出现段错误,而不是只输出数组的第一个。我可以看到第一个for-loop的输出。 - 我不会注释掉 couts 并且
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;
}
【问题讨论】:
-
我相信你内心的
for-loop会超过size。试试size - 1
标签: c++ arrays for-loop assembly segmentation-fault