简体   繁体   English

如何修复编译器警告 C6386 和 C6385?

[英]How do I fix compiler warnings C6386 and C6385?

For the program I am writing I need to create an array with a user-defined size, as well as random values between -15 and 15. As such i am using srand along with dynamic array casting.对于我正在编写的程序,我需要创建一个具有用户定义大小的数组,以及 -15 和 15 之间的随机值。因此,我将 srand 与动态数组转换一起使用。 This is my full code below:这是我下面的完整代码:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    //initialize variables
    double minValue;
    double maxValue;
    double firstQuartile;
    double thirdQuartile;
    double skewness;

    int size;
    std::cout << "Please enter the size of the data set: ";                 //get data set size from user
    std::cin >> size;
    int* dataSet = new int[size];                                                           
    cout << endl << "These are the randomly generated values: ";

    srand(static_cast<unsigned int>(time(NULL)));

    int i = size;
    for (int x = 0; x < i; x++)                                         //generate random numbers
    {
        dataSet[i] = (rand() % 31) - 15;
        cout << dataSet[i] << " ";
    }


} 

While it still compiles, I need it to do so without errors and the section I've highlighted below is causing two errors I do not know how to fix.虽然它仍然可以编译,但我需要它在没有错误的情况下这样做,而我在下面突出显示的部分导致了两个我不知道如何修复的错误。

int i = size;
    for (int x = 0; x < i; x++)                                         //generate random numbers
    {
        dataSet[i] = (rand() % 31) - 15;
        cout << dataSet[i] << " ";
    }

C6386 Buffer overrun while writing to 'dataSet': the writable size is 'size*4' bytes, but 'i' bytes might be written. C6386写入“dataSet”时缓冲区溢出:可写大小为“size*4”字节,但可能会写入“i”字节。

AND

C6385 Reading invalid data from 'dataSet': the readable size is 'size*4' bytes, but 'i' bytes may be read. C6385从'dataSet'读取无效数据:可读大小为'size*4'字节,但可以读取'i'字节。

In this loop the index variable x not i.在这个循环中索引变量 x 而不是 i。

So change the loop like所以像这样改变循环

int i = size;
for (int x = 0; x < i; x++)                                         //generate random numbers
{
    dataSet[x] = (rand() % 31) - 15;
    cout << dataSet[x] << " ";
}

In fact the variable i is redundant and makes the code error prone.事实上,变量 i 是多余的,使代码容易出错。 Why not to write为什么不写

for (int i = 0; i < size; i++)                                         //generate random numbers
{
    dataSet[i] = (rand() % 31) - 15;
    cout << dataSet[i] << " ";
}

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

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