简体   繁体   English

两个几乎完全相同的程序,但输出不同

[英]Two almost exactly the same programs but different output

Hi I have made a very simple program that should work but it don't: 嗨,我做了一个非常简单的程序,应该可以运行,但是不能:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int usedNumbers[256];
    memset(usedNumbers,0,256);

    srand(time(NULL));

    for(int i=0; i<256; ++i){
        while(1){
            int r = rand()%256;
            if( !usedNumbers[r] ){
                usedNumbers[r] = 1;
                break;
            }
            printf("Test: %03d -> %03d\n", i, r);
        }
    }

    return 0;
}

The idea of the program is to print numbers from 0 to 255 on the screen in the random order but the program stops on 84th number on 32 computers and 144th number on 64 bit computers. 该程序的想法是在屏幕上以随机顺序打印从0到255的数字,但是该程序在32台计算机上的第84个数字和64位计算机上的第144个数字上停止。 If i only move the "int usedNumbers[256];" 如果我只移动“ int usedNumbers [256];” above the function like that: 上面的功能是这样的:

#include <string.h>

int usedNumbers[256];

int main(int argc, char *argv[]) {

Program works as it supposed to. 程序按预期工作。 Why is it that? 怎么会这样 I am using the newest GNU/GCC compiler and C11 standard. 我正在使用最新的GNU / GCC编译器和C11标准。

The usedNumbers inside main is a local variable and these are not zero-initialized (ie they can contain garbage). 所述usedNumbers 里面 main是一个局部变量和这些都不是零初始化(即,它们可以含有垃圾)。 Since you only use memset(..., 256) , only the first 256 bytes are zero-initialized, and the rest (eg half or three quarters of the array -- or more, depending on the size of int ) is not. 由于仅使用memset(..., 256) ,因此只有前256 个字节被零初始化,而其余部分(例如,数组的一半或四分之三-或更多,取决于int的大小)没有被初始化。

The usedNumbers outside main is a global variable, however, and these are completely zero-initialized, even without memset . usedNumbers main是一个全局变量,但是,这些是完全零初始化,即使没有memset So there, you really have an empty array with no garbage in it, and that is why that works as expected. 在那里,您确实有一个没有垃圾的空数组,这就是为什么它能按预期工作的原因。

So do: 这样:

    memset(usedNumbers, 0, sizeof(usedNumbers));

and both versions should produce the same, expected result. 并且两个版本都应产生相同的预期结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM