[英]How can I fix my code so I don't get a C6385 warning?
I'm having trouble with a C6385 warning in my code.我的代码中出现 C6385 警告问题。 I'm trying to see if two arrays will equal each other.我正在尝试查看两个 arrays 是否彼此相等。 The warning I keep getting is on the line where if(p[i] == inputGuess[j]).我不断收到的警告在 if(p[i] == inputGuess[j]) 的行上。 I have tried redoing these line but I keep getting the same warning.我试过重做这些行,但我一直收到同样的警告。 Does anyone know what I'm doing wrong.有谁知道我做错了什么。 This is also my first time programming in C++.这也是我第一次在 C++ 中编程。
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
int* generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cout << numbers[i]<< " " << endl;
}
return numbers;
}
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; i < n; j++) {
if (p[i] == inputGuess[j]){ //Where I keep getting the C6385 Warning
sum++;
break;
}
}
}
}
The C6385 warning documentation states: C6385 警告文档指出:
The readable extent of the buffer might be smaller than the index used to read from it.缓冲区的可读范围可能小于用于从中读取的索引。 Attempts to read data outside the valid range leads to buffer overrun.尝试读取有效范围之外的数据会导致缓冲区溢出。
https://docs.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160 https://docs.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160
Your second if
statement compares i < n
instead of j < n
and since i
is never modified inside it will run forever.您的第二个if
语句比较i < n
而不是j < n
并且由于i
内部从未被修改过,它将永远运行。 This causes the warning since you'll access memory out of bounds.这会导致警告,因为您将越界访问 memory。 Fix the comparison.修正比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.