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

前端 未结 3 793
鱼传尺愫
鱼传尺愫 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<int> for dynamically sized arrays and std::array<int> for statically sized arrays.

    #include <array>
    using namespace std;
    
    array<array<int, 9>, 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<int, 9> temp = logic[2];
    
    0 讨论(0)
  • 2021-01-12 14:08

    As well as decaying the array to a pointer, you can also bind it to a reference:

    int (&temp)[9] = logic[2];
    

    One advantage of this is it will allow you to use it C++11 range-based for loops:

    for (auto t : temp) {
      // stuff
    }
    
    0 讨论(0)
  • 2021-01-12 14:20

    A direct assignment won't work. C++ does not allow that. At best you'll be able to assign them to point to the same data - int *temp = logic[2]. You'll need a for loop or something like the below.

    I believe this would work:

    int temp[9];
    memcpy(temp, logic[2], sizeof(temp));
    

    But I'd generally suggest using std::vector or std::array instead.

    0 讨论(0)
提交回复
热议问题