首页 > 解决方案 > “打印一个数组”如何改变另一个数组的值?

问题描述

我有两个数组,我只想输出后一个,但在输出中一个元素刚刚得到一个垃圾值。但是,如果我在它之前打印第一个数组,则不再输出第二个数组中的垃圾值(好吧,我必须编译并运行 3/4 次才能获得一次正确的值,剩下的 2/3次我得到垃圾值)

(我运行我的代码而不在 codechef.com/ide 中打印第一个数组,并且每次都给出了所需的输出。)

所以我有两个问题。

  1. 为什么会这样?

  2. 为什么这只发生在我的而不是oj?

我试图实现堆构建,即获取一个数组a,将该数组放入另一个名为heap的数组中,使遵循Binary Min Heap的属性。最后,打印heap的元素。当我编译并运行它时,它每次都输出一个垃圾值而不是某个元素的值。然后,为了调试它,我在打印之前进行了一个循环,以便打印a数组以查看它是否正确接收输入。这一次,数组打印正确!但是当我再次编译并运行它时,它给了我相同的垃圾值,而不是像以前一样的元素值。我刚开始编译和运行代码一段时间。我注意到,在每 3/4 次编译中,它只给出一次正确答案。

后来我在 codechef 的 ide 中提交了我的代码,这次我每次都得到正确的输出,而无需打印额外的数组a

#include <bits/stdc++.h>

using namespace std;

int main(void)
{ 
    int a[10];

    for (int i = 0; i < 6; i++)
    {
        cin >> a[i];
    }

    int heap[10];

    for (int i = 0, h = 1; i < 6; i++, h++)
    {
        if(h == 1) heap[h] = a[i];
        else{
            heap[h] = a[i];
            int k = h;
            //checking if the new heap element violates the heap property
            //if it does then swap with it's parent , and repeat
            while(k){
                if(heap[k] < heap[k/2]) swap(heap[k], heap[k/2]);
                k /= 2;
            }
        }
    }
    /* if this part is executed then the heap printing
    // part prints the correct heap array atleast one time
    // in every 3 or more than 3 "build & run" without any garbage value

    //if not executed, then the heap printing part prints a 
    //garbage value each and every time 
    */

    // weird start
    //prints the main array
    // for (int i = 0; i <= 5; ++i)
    // {
    //  cout << a[i] <<' ';
    // }
    // cout << endl;
    //weird end

    //heap printing part
    for (int i = 1; i <= 6; ++i)
    {
        cout << heap[i] << ' ';
    }
    cout << endl;
    return 0;
}

输入:6 5 1 4 2 3

我预计:1 2 3 6 4 5

我得到:2 4 3 6 5 4199040

(编辑:sublime text and codeblocks & 编译器:minGW)

更新:替换while(k)while(k/2)在没有任何帮助打印另一个数组的情况下输出答案的工作。但是代码是如何在我的设备中的几个构建和运行操作中生成两个不同的输出的呢?它每次都在在线 ide 中输出正确的答案,但在我的 ide 中却没有。这实际上是主要问题

标签: c++arraysdebuggingcompiler-constructionundefined-behavior

解决方案


推荐阅读