You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序调试问题:removeStuff函数循环中i值异常变为随机数

问题分析与解决

核心问题:非标准变长数组引发内存破坏

你的代码中使用了ll arr[n];这种变长数组(VLA),这是C语言特性,并非标准C++的一部分。虽然部分编译器(如GCC)会提供扩展支持,但栈上的变长数组极易引发栈溢出或内存越界,这正是removeStuff函数中循环变量i变成随机值的直接原因——内存被非法覆盖,破坏了循环变量的存储。

次要问题:逻辑缺陷无法处理多元素移除场景

removeStuff的循环逻辑仅处理单次移除元素的情况,当需要移除多个元素才能让sum等于target时,当前逻辑会直接跳过,无法完成sum的调整。


修复后的代码

#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define ll long long

void printArray(const vector<ll>& arr) {
    string w;
    ll count = 0;
    for (ll num : arr) {
        if (num != 0) {
            count++;
            w += to_string(num) + " ";
        }
    }
    cout << count << " " << w << endl;
}

void adjustSum(vector<ll>& arr, ll target, ll currentSum) {
    if (currentSum == target) {
        printArray(arr);
        return;
    }

    // 从大到小移除元素,直到sum匹配target
    for (size_t i = arr.size() - 1; i < arr.size(); i--) {
        if (arr[i] == 0) continue;
        if (currentSum - arr[i] >= target) {
            currentSum -= arr[i];
            arr[i] = 0;
            if (currentSum == target) {
                printArray(arr);
                return;
            }
        }
    }
}

ll sum(ll n) {
    return (n * (n + 1)) / 2;
}

int main() {
    ios::sync_with_stdio(false);
    int testCases;
    cin >> testCases;

    while (testCases--) {
        ll n, s;
        cin >> n >> s;
        ll totalSum = sum(n);
        if (totalSum < s) {
            cout << -1 << endl;
            continue;
        } else if (totalSum == s) {
            string w;
            for (ll i = 1; i <= n; i++) {
                w += " " + to_string(i);
            }
            cout << n << " " << w << endl;
            continue;
        } else {
            if (n >= s) {
                cout << "1 " << s << endl;
                continue;
            } else if (s - n > 0 && s - n < n) {
                cout << "2 " << n << " " << s - n << endl;
                continue;
            } else {
                vector<ll> arr(n);
                ll currentSum = 0;
                for (ll i = 0; i < n; i++) {
                    arr[i] = i + 1;
                    currentSum += arr[i];
                }
                adjustSum(arr, s, currentSum);
            }
        }
    }
}

关键修改点

  • 用标准容器vector<ll>替代变长数组,彻底避免栈内存问题。
  • 重构adjustSum函数逻辑,确保能持续移除元素直到sum等于target。
  • 使用size_t作为容器索引类型,避免负数索引导致的未定义行为。
  • 修正原main函数中判断双元素组合的逻辑错误,确保两个数都是1到n之间的不同正整数。

内容的提问来源于stack exchange,提问作者Ismail Fateen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:03:15