繁体   English   中英

VS 中的 C6385 警告(关于动态数组)

[英]C6385 warning in VS (in regard to dynamic arrays)

我的代码应该打印两组整数的并集和交集。 为什么我会收到此警告?

截屏

是不是因为我使用动态数组并且它的大小在运行时可以是任何东西?

我该如何解决? 我的代码工作正常,但这个警告真的让我很烦恼。

PS:我知道使用std::vector会容易std::vector但我的老师要求使用数组。

#include <iostream>

using namespace std;

void UnionFunc(int[],int,int[],int,int[],int&);
void IntersectionFunc(int[], int, int[], int, int[], int&);

int main() {
    int* A;
    int SizeA;
    int* B;
    int SizeB;
    int* Union;
    int UnionSize=0;
    int* Intersection;
    int IntersectionSize=0;

    cout << "Enter the Size of First Set : "; cin >> SizeA;
    A = new int[SizeA];
    cout << "Enter the Size of Second Set : "; cin >> SizeB;
    B = new int[SizeB];
    Intersection = new int[SizeA >= SizeB ? SizeB : SizeA];
    Union = new int[SizeA + SizeB];

    for (int i = 0; i < SizeA; i++) {
        cout << "Set A[" << i + 1 << "] = ";
        cin >> A[i];
    }
    for (int i = 0; i < SizeB; i++) {
        cout << "Set B[" << i + 1 << "] = ";
        cin >> B[i];
    }
    
    UnionFunc(A,SizeA,B,SizeB,Union,UnionSize);
    IntersectionFunc(A, SizeA, B, SizeB, Intersection, IntersectionSize);

    cout <<endl<< "Union Set : ";
    for (int i = 0; i < UnionSize; i++) {
        cout << Union[i] << ",";
    }

    cout <<endl <<"Intersection Set : ";
    for (int i = 0; i < IntersectionSize; i++) {
        cout << Intersection[i] << ",";
    }


    system("pause>n");
    return 0;
}

void UnionFunc(int A[],int SizeA, int B[],int SizeB, int Union[],int &UnionSize) {
    
    //Adding First Array to Union Array
    for (int i = 0; i < SizeA;i++) {
        Union[i] = A[i];
        UnionSize++;
    }

    //Checking if second array's elemnts already exist in union arry, if not adding them
    bool exist;

    for (int i = 0; i < SizeB; i++) {
        exist = false;
        for (int j = 0; j < UnionSize; j++) {
            if (B[i] == Union[j] ) {
                exist = true;
            }
        }
        if (exist == false) {
            Union[UnionSize] = B[i];
            UnionSize++;
        }
    }

}

void IntersectionFunc(int A[], int SizeA, int B[], int SizeB, int Intersection[], int& IntersectionSize) {
    for (int i = 0; i < SizeA; i++) {
        for (int j = 0; j < SizeB; j++) {
            if (A[i] == B[j]) {
                Intersection[IntersectionSize] = A[i];
                IntersectionSize++;
            }
        }
    }

}

是不是因为我使用动态数组并且它的大小在运行时可以是任何东西?

是的! 编译器不知道(并且,在编写代码时,知道) SizeASizeB都是“有效”数字 - 因此您创建的三个int数组的大小可能小于Intersection[i] 'read' 有效。

对此的“快速而肮脏”的修复是向编译器提供可见的保证,即您创建的数组将至少具有特定大小,如下所示:

A = new int[max(1,SizeA)]; // Compiler can now 'see' a minimum size

同样,对于您使用new[]运算符进行的其他分配。

(我与VS2019测试此,加入max(1,SizeA)max(1,SizeB) “修复”来的只是分配AB并且警告被去除。)

暂无
暂无

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

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