gpt4 book ai didi

c++ - 计算机内存中发生了什么?

转载 作者:太空狗 更新时间:2023-10-29 23:24:35 24 4
gpt4 key购买 nike

所以我的教授告诉我的类(class)运行这个程序,它可以显示计算机内存中正在发生的事情。当我运行它时,我的输出文件与教授输出文件的前 4 行数字相同,然后是完全不同的数字。但这肯定不像是在拉随机数,因为很多输出都是 0,而且很多都是长度相似的大量数字。谁能解释一下?

#include <iostream>
#include <fstream> // for files
#include <cstdlib> // for exit
#include <climits> // for INT_MAX etc.
int main( )
{
using namespace std;

ofstream outfile;
outfile.open("Whats_in_computer_memory.txt");

cout << "In this program, we declare a small array and then use array syntax " << endl
<< "to see what is in the computer's memory. " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl
<< " " << endl;

int a[1];

int histogram[214749];

for (int i = 0; i < 214749; i++ )
{
histogram[i] = 0;
}
cout << "&a[0] = " << &a[0] << endl
<< "&histogram[0] = " << &histogram[0]<< endl
<< " " << endl;

cout << INT_MAX << endl;

for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}

for (int i = 0; i < 2 ; i++ )
{
cout << histogram[ i ] << endl;
}


char dummy;

cin >> dummy;
return 0;

最佳答案

a 有一个元素。这意味着

for (int i = 0; i < 1000; i++ )
{
outfile << a[i] << endl;
//cout << INT_MAX/1000000 +a[i]/1000000 << endl;
//histogram[ a[i]/1000000 ]++;
}

undefined behavior一旦 i >= 1。一旦你有未定义的行为,任何事情都可能发生,所以我们无法再推断出发生了什么。

关于c++ - 计算机内存中发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com