简体   繁体   English

C++ 阵列中的 C6385 和 C6201 警告

[英]C6385 & C6201 Warning in C++ array

i get a warning messages while doing merge between two sorted arrays into one sorted array as follows: and the error or warning messages that come to me are: C6385 & C6201我在将两个排序的 arrays 合并为一个排序数组时收到一条警告消息,如下所示:并且出现的错误或警告消息是:C6385 和 C6201

#include <iostream>
using namespace std;

int main()
{
    int arr1[5] = { 1,3,5,7,9 }, arr2[5] = { 0,2,4,6,8 }, arr3[10];

    for (int i = 1; i <= 9; i++)
        if (arr1[i] < arr2[i])
            arr3[i] = arr1[i];
        else
            arr3[i] = arr2[i];
        cout << arr3[10] << endl;

    return 0;
}

Array indices in C++ start from 0. C++ 中的数组索引从 0 开始。

Also this statement还有这个说法

cout << arr3[10] << endl;

does not output the array.没有 output 阵列。 It tries to output a non-existent element with index 10 of the array.它尝试 output 数组索引为 10 的不存在元素。

And the loop is invalid because it tries to access memory beyond the arrays arr1 and arr2.并且该循环无效,因为它试图访问 memory 超出 arrays arr1 和 arr2。

Your program can look the following way.您的程序可以如下所示。

#include <iostream>
using namespace std;

int main()
{
    const size_t N = 5;
    int arr1[N] = { 1,3,5,7,9 }, arr2[N] = { 0,2,4,6,8 }, arr3[2 * N];

    for ( size_t i = 0, j = 0, k = 0; i < 2 * N; i++)
    {
        if ( arr2[k] < arr1[j])
            arr3[i] = arr2[k++];
        else
            arr3[i] = arr1[j++];
    }

    for ( const auto &item : arr3 ) cout << item << ' ';
    cout << '\n';

    return 0;
}

The same task can be performed with using the standard algorithm std::merge declared in the header <algorithm> .使用 header <algorithm>中声明的标准算法std::merge可以执行相同的任务。

For example例如

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    int a1[] = { 1, 3, 5, 7, 9 };
    int a2[] = { 0, 2, 4, 6, 8 };
    int a3[sizeof( a1 ) / sizeof( *a1 ) + sizeof( a2 ) / sizeof( *a2 )];

    std::merge( std::begin( a1 ), std::end( a1 ),
                std::begin( a2 ), std::end( a2 ),
                std::begin( a3 ) );

    for ( const auto &item : a3 ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

The program output is the same as shown above.程序 output 与上图相同。

0 1 2 3 4 5 6 7 8 9 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM