【问题标题】:Why is a variable I've scanned changing upon scanning a separate array? [duplicate]为什么我扫描的变量在扫描单独的数组时会发生变化? [复制]
【发布时间】:2022-01-06 13:15:05
【问题描述】:

我在 HackerRank 上经历了 C++ 的挑战,但我一直卡在数组介绍上。它给了我一个示例输入

4
1 4 3 2

其中 n=4 是数组的大小,下一行给出了具有 n 个随机整数的数组。我在回答问题时遇到了第一个 for 循环后 n=4 更改的问题,所以我一直在弄乱它以试图理解它。

目前,我只是尝试扫描样本输入数字,但一旦我扫描了数组的最后一个元素,n 就会不断变化:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    int n, arr[n];
    scanf("%d", &n);
    printf("%d \n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        printf("%d ", arr[i]);
        printf("n=");
        printf("%d ", n);
    }
    printf("\n%d", n);
    return 0;
}

这给了我以下输出:

4
1 n=4 4 n=4 3 n=4 2 n=2
2

谁能解释为什么 n 在最后一个循环之后变为 2 并在所有后续使用中保持为 n=2 ?当我没有将它分配给任何东西时,它会受到什么影响?这是他们给我作为练习的唯一示例输入,但在我提交后他们尝试了更多 1

【问题讨论】:

  • int n, arr[n]; -- 这应该做什么?我建议您不要从“竞争”网站学习正确的 C++ 编程。这在很多方面都是错误的。
  • 当你声明arr[n]时,此时n是什么?你在哪里学会使用这样的数组?事实上,就标准而言,这不是合法的 C++。也许暂停挑战,获取good C++ book 并首先学习基础知识。
  • 补充@churill 所说的内容,没有任何具有任何声誉的C++ 书籍会像您声明的那样声明数组。原因很简单——您拥有的代码不是有效的 C++。如果您从正确的阅读材料中学习 C++,您将使用 std::vector&lt;int&gt; arr(n);(在将 n 设置为已知值之后)。此外,hackerrank 等网站假设您知道要用来回答他们问题的语言,足以避免像您犯的那样犯简单的错误。 Hackerrank 和类似的网站不是在教你 C++。
  • 感谢@PaulMcKenzie 和 churill 抽出宝贵时间回答。我没有意识到这种熟悉 C++ 的方法对适当的编码人员来说是如此令人愤怒。我会听从你的建议,买一本书。

标签: c++ arrays scanf


【解决方案1】:

首先在C++中,数组的大小必须是编译时常数。所以,以下面的代码sn-ps为例:

int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression

上面的正确写法是:

const int n = 10;
int arr[n]; //CORRECT

同样,以下(您在代码示例中所做的)不正确:

int n, arr[n]; //INCORRECT, Note n has garbage value and using this garbage value leads 
              //to undefined behavior and also n is not a constant expression

注意上面的语句有2个问题:

首先因为你还没有初始化n,它有垃圾值,你正在使用的垃圾值是未定义的行为

第二 n 不是常量表达式。

要解决这个问题,你应该使用std::vector而不是使用内置数组,如下所示:


#include <vector>
#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    std::cin >> n;
    //create a vector of size n 
    std::vector<int> arr(n);
    
    printf("%d \n", n);
    //iterator through the vector
    for (int &element: arr) {
        std::cin >> element ;
        std::cout<<element <<" ";
        //add other code here
    }
   
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多