“ cout << count << endl;”没有打印任何东西

时间:2019-09-08 12:19:54

标签: c++ printing output missing-data

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

输出不包含任何内容

1 个答案:

答案 0 :(得分:1)

您应该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[]
}