C++提取数组奇数排序输出时出现异常大数值问题排查
问题原因分析
你代码中遍历提取奇数的for循环存在2个核心问题:
- 奇数下标变量初始化位置错误
当前你在遍历原数组的循环内部每次都重置p = 0,这会导致所有奇数都会被写入odd[0]的位置,后写入的奇数会覆盖之前的数值,最终odd数组中仅最后一个找到的奇数有效,其余位置全部是未初始化的栈内存垃圾值,这就是你输出异常大数值的根本原因。 - 使用非标准的可变长度数组
int a[n]、int odd[n]属于C语言的可变长度数组特性,不属于C++标准语法,仅部分编译器做了扩展支持,存在兼容性风险。
修正方案
1. 调整p的初始化位置
将p的初始化移到遍历原数组的循环外层,每个测试用例初始化一次即可:
for (int i = 0; i < T; i++) { cin >> n; int a[n]; int odd[n]; int p = 0; // 每个测试用例开始时初始化奇数存储下标 for (int j = 0; j < n; j++) { cin >> a[j]; } for (int j = 0; j < n; j++) { if (a[j] % 2 != 0){ odd[p++] = a[j]; si++; } } selectionSort(odd, si);
2. (可选)替换为标准C++动态数组
使用std::vector替换可变长度数组,兼容所有标准C++编译器:
// 需要先引入头文件 #include <vector> for (int i = 0; i < T; i++) { cin >> n; vector<int> a(n); vector<int> odd; odd.reserve(n); // 预分配空间避免多次扩容 int si = 0; for (int j = 0; j < n; j++) { cin >> a[j]; } for (int j = 0; j < n; j++) { if (a[j] % 2 != 0){ odd.push_back(a[j]); si++; } } selectionSort(odd.data(), si);
修正后即可得到符合预期的输出结果。
内容的提问来源于stack exchange,提问作者Kushagra Agrawal
相关产品推荐
相关产品推荐

