简体   繁体   English

在C ++中将两个3 x 3数组连接为一个数组

[英]Concatenating two 3 by 3 arrays into one array in C++

As the title indicates, I want to concatenate two arrays into one larger array. 如标题所示,我想将两个数组连接成一个更大的数组。 for example: 例如:

array1= 1  2  3
        4  5  6
        7  8  9
array1= 10  20  30
        40  50  60
        70  80  90
array3= 1  2  3  10  20  30
        4  5  6  40  50  60
        7  8  9  70  80  90

So, I wrote this code: 因此,我编写了以下代码:

#include <iostream>

using namespace std;

int main()
{
    int array1[3][3],array2[3][3],array3[3][6];
    int i,j;

    //Matrix 1 input
    cout<<"Enter matrix 1\n";
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
        {
            cin>>array1[i][j];
            array3[i][j]=array1[i][j]; //Assigning array1 values to array3
        }
    }

    //array2 input
    cout<<"Enter matrix 2\n";
    for (i=0;i<3;i++)
    {
        for (j=3;j<6;j++)
        {
            cin>>array2[i][j];
            array3[i][j]=array2[i][j]; //Assigning array2 values to array3
        }
    }

    //array3 output
    cout<<"New matrix is\n";
    for (i=0;i<3;i++)
    {
        for (j=0;j<6;j++)
        {
            cout<<array3[i][j]<<"\t";
        }
    cout<<"\n";
    }
}

But when I execute it, I ended up with last row of array2 being the (2,3), (2,4) and (2,5) elements (which is right), but also being the (0,1), (0,2) and (0,3) elemnts (which should be [1 2 3]). 但是,当我执行它时,我最后得到array2的最后一行是(2,3),(2,4)和(2,5)元素(是正确的),但也是(0,1), (0,2)和(0,3)元素(应为[1 2 3])。

array3= 70  80  90  10  20  30
        4   5    6  40  50  60
        7   8    9  70  80  90

So, what's happening here? 那么,这是怎么回事?

EDIT: I did the following: 编辑:我做了以下:

for (i=0;i<3;i++)
{
    for (j=0;j<3;j++)
    {
        cin>>array2[i][j];
        array3[i][j+3]=array2[i][j]; //Assigning array2 values to array3 and adding 3 to j
    }

And it went ok. 一切顺利。 Is the method I used "professional"? 我使用的方法是“专业”吗? } }

This is undefined behavior: 这是未定义的行为:

for (i=0;i<3;i++)
    for (j=3;j<6;j++)
        array3[i][j]=array2[i][j];

array2 is 3x3 but you're indexing into it starting with [0][3] which is an error. array2是3x3,但是您array2 [0] [3]开始对其进行索引,这是一个错误。 You could get runtime checking of this sort of thing if you used C++11 std::array and its .at() method instead of raw C arrays. 如果使用C ++ 11 std::array及其.at()方法而不是原始C数组,则可以对这种情况进行运行时检查。

array2 is a 3x3 array and you use j indices between 3 and 6 : you access outside of your matrix anywhere in memory. array2是一个3x3数组,您使用3到6之间的j索引:您可以在矩阵的外部访问内存中的任何位置

You should instead write (eg) : 您应该改写(例如):

//array2 input
cout<<"Enter matrix 2\n";
for (i=0;i<3;i++)
{
    for (j=0;j<3;j++)
    {
        cin>>array2[i][j]; // j is correct for array2
        array3[i][j+3]=array2[i][j]; //Assigning array2 values to array3
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM