用C ++添加两个2D数组 - 为什么这个程序会崩溃?

时间:2017-03-19 10:24:22

标签: c++ arrays multidimensional-array sum integer

嘿,我是C ++编程的初学者。我制作了一个程序,用于将两个2D阵列一起添加。但是,程序输出值直到程序崩溃。有人可以帮助我找出问题吗?

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    int a[10][10], c[10][10], i, j;
    for (i = 1; i <= 10; ++i)
    {
        for(j=0; j < 10; ++j)
        {
            a[i][j] = i * j; 
        }
    }

    // We are able to treat the individual columns as arrays
    for (int i = 0; i < 10; ++i)
    {
        int *b = a[i];
        for (int j = 0; j < 10; ++j)
        {
            cout << b[j] << " ";
        }

        cout << endl;
    }

    cout << "****" << endl;

    // Declare a multidimensional array on the heap
    int **b = new int*[10];

    // need to allocate all members individually
    for (int i = 0; i < 10; ++i)
    {
        b[i] = new int[10];
    }

    // Set the values of b
    for (int i = 0; i < 10; ++i)
    {
        for (j = 0; j < 10; ++j)
        {
            b[i][j] = (i * 10) + j; 
        }
    }

    for (i = 0; i < 10; ++i)
    {
        for (j = 1; j <= 10; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }

    for (i = 0; i < 10; ++i)
    {
        for (j = 1; j <= 10; ++j)
        {
            cout << c[i][j] << endl; 
        }
    }

    // Delete the multidimensional array - have to delete each part 
    for (int i = 0; i < 10; ++i)
    {
        delete[] b[i];
    }
    delete[] b;

    return 0; 
}

1 个答案:

答案 0 :(得分:0)

我纠正了你的代码。现在,它正在运行,程序没有崩溃。你可以尝试一下。

#include<conio.h>
#include<iostream.h>

int main(int argc, char** argv)
{
    int a[10][10], c[10][10], i, j;
    for (i = 0; i <10; ++i)
    {
        for(j=0; j < 10; ++j)
        {
            a[i][j] = i * j;
        }
    }

    //We are able to treat the individual columns as arrays;
    for (i = 0; i < 10; ++i)
    {
        int *b = a[i];
        for (int j = 0; j < 10; ++j)
        {
            cout << b[j] << " ";
        }
        cout << endl;
    }
    cout << "****" << endl;
    //Declare a multidimensional array on the heap;
    int **b = new int*[10];
    //need to allocate all members individually
    for (i = 0; i < 10; ++i)
    {
        b[i] = new int[10];
    }
    //Set the values of b
    for ( i = 0; i < 10; ++i)
    {
       for (j = 0; j < 10; ++j)
       {
           b[i][j] = (i * 10) + j;
       }
    }
    for (i = 0; i < 10; ++i)
    {
        for (j = 0; j <10; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }

    for (i = 0; i < 10; ++i)
    {
        for (j = 0;j < 10; ++j)
        {
            cout << c[i][j] << " ";
        }
        cout<<endl;
    }

//  Delete the multidimensional array - have to delete each part
    for (i = 0; i < 10; ++i)
    {
        delete[] b[i];
    }
    delete[] b;
    return 0;
}