首页 > 解决方案 > C++ 问题,其中分配给变量的值正在更改,即使它尚未修改

问题描述

请帮助我解决这个奇怪的问题,其中输入值为 4(即 n = 4),并且在 for 循环之后,相同的值显示为 2,但为什么呢?它没有在任何地方使用(AFAIK),也不应该改变(我对此一无所知)。

HackerRank上的原始问题。

我的代码>>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    int arr[n];
    cin >> n; // input given from stdin is 4
    
    cout << n << "\n"; // outputs 4
    
    for(int i=0; i<n; i++){
        scanf("%d",&arr[i]);
    }
    
    cout << n << "\n"; // outputs 2 (but why?)
    
    for(int i=n-1; i>=0; i--){
        printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
    }
    return 0;
}

感谢您的任何帮助!

标签: c++variables

解决方案


int n;
int arr[n];   // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4

首先,这在 C++ 中甚至是不合法的。作为支持 C 风格 VLA 的 gcc 扩展,看到数组声明时 n 的值是多少?你还没读过!!


相反,使用:

int n;
cin >> n;
std::vector arr(n);

尽管这仍然不是“C++ 方式”,因为您要预先定义整个集合,然后依次分配给每个元素;而不是将每个元素添加到集合中。这不是什么大问题,int但更一般地说,您不希望集合中未使用的项目死亡;相反,它们根本不存在。

std::vector arr;  // don't pre-allocate any size
for(int i=0; i<n; i++){
        int val;
        scanf("%d",&val);   //<<<   uhhhhhh.  you know about `cin` why this?
        arr.push_back(val);
    }

推荐阅读