Accessing an entire row of a multidimensional array in C++

前端 未结 3 795
鱼传尺愫
鱼传尺愫 2021-01-12 13:47

How would one access an entire row of a multidimensional array? For example:

int logic[4][9] = {
    {0,1,8,8,8,8,8,1,1},
    {1,0,1,1,8,8,8,1,1},
    {8,1,0         


        
3条回答
  •  逝去的感伤
    2021-01-12 14:02

    That's not how arrays/pointers work in C++.

    That array is stored somewhere in memory. In order to reference the same data, you'll want a pointer that points to the the beginning of the array:

    int* temp = logic[2];
    

    Or if you need a copy of that array, you'll have to allocate more space.

    Statically:

    int temp[9];
    for (int i = 0; i < 9; i++) {
        temp[i] = logic[2][i];
    }
    

    Dynamically:

    // allocate
    int* temp = new int(9);
    for (int i = 0; i < 9; i++) {
        temp[i] = logic[2][i];
    }
    
    // when you're done with it, deallocate
    delete [] temp;
    

    Or since you're using C++, if you want to not worry about all this memory stuff and pointers, then you should use std::vector for dynamically sized arrays and std::array for statically sized arrays.

    #include 
    using namespace std;
    
    array, 4> logic = {
      {0,1,8,8,8,8,8,1,1},
      {1,0,1,1,8,8,8,1,1},
      {8,1,0,1,8,8,8,8,1},
      {8,1,1,0,1,1,8,8,1}
    }};
    
    array temp = logic[2];
    

提交回复
热议问题