C++数组分析函数输出垃圾值问题求助
问题分析与解决方案
你的代码存在两个核心问题,直接导致了函数输出垃圾值:
1. 未调用函数就打印未初始化变量
在main函数中,你定义了int sum, max, min;但从未调用对应的sum()、max()、min()函数为这些变量赋值,直接打印的是未初始化的局部变量,自然会输出垃圾值。同时,变量名和全局函数名重名会遮蔽函数,建议修改变量名避免冲突。
2. 数组越界写入
fillArray函数中的循环条件错误:r <= Ro和c <= Co。数组下标从0开始,合法范围是0 <= r < Ro、0 <= c < Co,越界写入会破坏内存,引发未定义行为。
修正后的完整代码
#include <iostream> #include <iomanip> #include <fstream> #include <cstdlib> #include <ctime> // 补充time函数依赖的头文件 using namespace std; const int Ro = 4; const int Co = 5; void fillArray(int myArray[Ro][Co]); void printArray(int myArray[Ro][Co]); void doubleArray(int myArray[Ro][Co]); int max(int myArray[Ro][Co]); int min(int myArray[Ro][Co]); int sum(int myArray[Ro][Co]); int main() { srand(time(NULL)); int myArray[Ro][Co]; // 修改变量名,避免与全局函数名冲突 int sum_val, max_val, min_val; cout << "\n\n\n"; fillArray(myArray); printArray(myArray); // 调用函数并为变量赋值 max_val = max(myArray); min_val = min(myArray); sum_val = sum(myArray); cout << "\n"; cout << "The largest number is : " << max_val; cout << "\n"; cout << "The smallest number is : " << min_val; cout << "\n"; cout << "The sum is : " << sum_val; cout << "\n\n"; doubleArray(myArray); printArray(myArray); return 0; } void fillArray(int myArray[Ro][Co]){ // 修正循环条件,避免数组越界 for (int r = 0; r < Ro; r++) { for(int c = 0; c < Co; c++){ myArray[r][c] = (rand()%100); } } } void printArray(int myArray[Ro][Co]){ for(int r = 0; r < Ro; r++){ for(int c = 0; c < Co; c++){ cout << myArray[r][c] << " "; } cout << "\n"; } } void doubleArray(int myArray[Ro][Co]){ for(int r = 0; r < Ro; r++){ for(int c = 0; c < Co; c++){ myArray[r][c] = myArray[r][c]*2; } } } int max(int myArray[Ro][Co]) { int max = myArray[0][0]; for(int r = 0; r < Ro; r++) { for(int c = 0; c < Co; c++) { if(myArray[r][c] > max){ max = myArray[r][c]; } } } return max; } int min(int myArray[Ro][Co]) { int min = myArray[0][0]; for(int r = 0; r < Ro; r++) { for(int c = 0; c < Co; c++) { if(myArray[r][c] < min){ min = myArray[r][c]; } } } return min; } int sum(int myArray[Ro][Co]) { int sum = 0; for(int r = 0; r < Ro; r++) { for(int c = 0; c < Co; c++) { sum += myArray[r][c]; } } return sum; }
额外说明
- 补充了
<ctime>头文件,time()函数需要该头文件支持,避免编译警告。 - 修改了
main中的变量名,防止全局函数被局部变量遮蔽,确保函数能正常调用。
内容的提问来源于stack exchange,提问作者Azphyxia
相关产品推荐
相关产品推荐

