c++ - 运行时检查失败 #02,随机数添加到数组

标签 c++ arrays sorting runtime-error

我编写了一个小程序来对数组进行排序。当我运行它时,它完成了它的工作,但似乎向数组添加了一个随机数。我也收到标题中显示的错误。

#include "stdafx.h"
#include <iostream>
#include <algorithm>

void printArray(int nArray[], int nSize) {
using namespace std;
for (int jjj = 0; jjj <= nSize; jjj++)
    cout << nArray[jjj] << " ";
cout << endl;
}

void sortArray(int nArray[], int nSize, bool bPrint) {   // bPrint is used to wether print after every step or not

 for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++) {    // Durch jeden Teil des Arrays gehen
    int nSmallestIndex = nStartIndex;   // Den aktuellen Startindex als kleinsten nehmen

    for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex <= nSize; nCurrentIndex++) {
        if (nArray[nCurrentIndex] < nArray[nSmallestIndex])
            nSmallestIndex = nCurrentIndex;
    }
    using namespace std;

    swap(nArray[nStartIndex], nArray[nSmallestIndex]);
    if (bPrint) {
        cout << "Swapping " << nArray[nStartIndex] << " and " << nArray[nSmallestIndex] << endl;
        printArray(nArray, nSize);
    }
  }

}

int main() {
    const int nSize = 7;
    int nArray[nSize] = { 3, 1, 5, 8, 2, 4, 6 };
    printArray(nArray, nSize);
    sortArray(nArray, nSize, true);
    std::cout << std::endl;
    system("pause");
    return 0;
}

最佳答案

你有两次 <= nSize ,应该是< nSize .在 C++ 中,如果数组的大小为 N , 有效索引为 0通过N-1 .

关于c++ - 运行时检查失败 #02,随机数添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880561/

相关文章:

arrays - BigQuery 将列转换为 RECORD

arrays - Mongoose 模式需要可以为空的数组

java - 为什么我的方法没有按照我想要的方式对矩阵中的列进行排序?

python - Sorted() 排序不正确

C++:将 boost::optional<type> 转换为类型的最安全方法

c++ - 如何将 std::chrono::time_point 转换为带有小数秒的日历日期时间字符串?

c++ - Qt - QTcpSocekt 无法检测到连接丢失

javascript - onClick 将其插入数组

python - 获取列表升序的索引

c++ - D 中的可变函数调用