>a; int **b; b=new int*[a]; -6ren">
gpt4 book ai didi

c++ - "cout<
转载 作者:行者123 更新时间:2023-11-28 04:10:44 25 4
gpt4 key购买 nike

cout<<count<<endl;应该根据条件提供输出,但它不打印任何内容,导致此类结果的代码中的故障/错误/缺陷是什么?这是我的第一个问题,如果我不能完全理解,请见谅。

我用了下面的代码,我不明白这里发生了什么。这是一个简单的输入输出问题。输出为我们提供了有关匹配两支球队制服的信息。

#include <stdio.h>
#include <iostream>

using namespace std;

main(){
int a;
cin>>a;
int **b;
b=new int*[a];
for (int i = 0; i < a; i++)
{
b[i]=new int[2];
for (int j = 0; j <2 ; j++)
{
cin>>b[i][j];
}
}

int count=0;
for (int i = 0; i < a*(a-1); i++)
{ for (int j = 0; j < a; j++)
if (b[i][0]==b[j][1])
count=count+1;
}
cout<<count<<endl;

for (size_t i = 0; i < a; i++)
{
delete b[i];
}
delete b;

}

输入:

3
1 2
2 4
3 4

输出不包含任何内容

最佳答案

您越界使用了数组,并且在您应该delete[]delete。代码注释:

#include <iostream> // use the correct headers
#include <cstddef>

// not recommended: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
using namespace std;

int main() { // main must return int
size_t a; // better type for an array size
cin >> a;
int** b;
b = new int*[a];
for(size_t i = 0; i < a; i++) {
b[i] = new int[2];
for(size_t j = 0; j < 2; j++) {
cin >> b[i][j];
}
}

int count = 0;
std::cout << a * (a - 1) << "\n"; // will print 6 for the given input
for(size_t i = 0; i < a * (a - 1); i++) {
// i will be in the range [0, 5]
for(size_t j = 0; j < a; j++)
if(b[i][0] == b[j][1]) count = count + 1;
// ^ undefined behaviour
}
cout << count << endl;

for(size_t i = 0; i < a; i++) {
delete[] b[i]; // use delete[] when you've used new[]
}
delete[] b; // use delete[] when you've used new[]
}

关于c++ - "cout<<count<<endl;"没有打印任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841905/

25 4 0

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