gpt4 book ai didi

c++ - 创建数组并从中检索数据时 C++ 中的未定义行为

转载 作者:行者123 更新时间:2023-11-28 01:23:18 25 4
gpt4 key购买 nike

我有未定义的行为,因为我是 C++ 的初学者,我什至不知道如何解决这个问题。我在看this link , 它显示了可能的错误。我唯一的猜测是我应该使用 malloc 吗?

#include <iostream>
using namespace std;

int main()
{

int population[100];

for (int i = 0; i < 100; ++i)
{
population[i] = rand()%(10);
}

int firstTournament[2];
int secondTournament[2];

int randomNumbers[4] = {};

for (int i = 0; i < 4; ++i)
{
int indexOfIndividual = rand()%(101);
randomNumbers[i] = indexOfIndividual;
}

for(int i = 0; i < 4; i++)
{
if(i < 2)
{
firstTournament[i] = population[randomNumbers[i]];
cout << "first tournament " << firstTournament[i] <<endl;
}
else
{
secondTournament[i] = population[randomNumbers[i]];
cout << "second tournament " << secondTournament[i] <<endl;
}
}

for (int i = 0; i < 2; ++i)
{
// This is where the problem starts. It prints gibberish
cout << "before tournament first " << firstTournament[i] << endl;
cout << "before tournament second " << secondTournament[i] << endl;
}

return 0;
}

这是打印出来的:

first tournament 4
first tournament 6
second tournament 5
second tournament 3

//This is where the fun begins:
before tournament first 4 // so far correct
before tournament second -1834234234 // ???
before tournament first 6 // correct
before tournament second 3266 // the numbers are supposed to be between 0 and 10

我该如何解决这个问题?我究竟做错了什么?

编译运行

g++ -std=c++11 -c -I /stuff/include main.cc

最佳答案

你的程序逻辑有问题。这是您填充 secondTournament 的地方:

for(int i = 0; i < 4; i++)
{
if(i < 2)
{
firstTournament[i] = population[randomNumbers[i]];
cout << "first tournament " << firstTournament[i] <<endl;
}
else
{
secondTournament[i] = population[randomNumbers[i]];
cout << "second tournament " << secondTournament[i] <<endl;
}
}

secondTournament[0]永远不会设置。因为当i0 , if(i < 2)truesecondTournament[i] = ...没有被执行。稍后,在这个 block 中:

 for (int i = 0; i < 2; ++i)
{
// This is where the problem starts. It prints gibberish
cout << "before tournament first " << firstTournament[i] << endl;
cout << "before tournament second " << secondTournament[i] << endl;
}

您正在打印 secondTournament[0]那不是设定的。相反,您正在设置 secondTournament[2]secondTournament[3] , 两者都超出范围。也许你想要的是 secondTournament[i-2] = ... .

关于c++ - 创建数组并从中检索数据时 C++ 中的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160619/

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