سؤال

I have 3 arrays, A[5][3][5], B[5][4][5], C[5][2][5]. Is it possible to access them by an array of pointers, with their second dimension being different? Something like:

int A[5][3][5], B[5][4][5], C[5][2][5];
int ***D[3];
D[0] = A;
D[1] = B;
D[2] = C;

I know this is wrong, I just want to know if it's possible to access them by one array?

هل كانت مفيدة؟

المحلول

No, if the second dimension is different it won't work. The best you can do is something like this:

struct arr {
    int *p; // pointer to first element
    int x, y, z; // array size
    int &at(int i, int j, int k) {
        return p[((i*y)+j)*z+k];
    }
}

Or you can use your favorite multidimensional array library. C++ lacks built-in support for multidimensional arrays unless all but the first size is known at compile time, and C99 VLAs won't work in this situation. This is because C/C++ use the type of the array to figure out how big it is in each dimension (except the first dimension, which can be unspecified).

نصائح أخرى

It's definitely not possible to do what you want directly due to the type system's restrictions, but you may want to consider something like the following (in C++11 syntax):

#include <vector>
#include <array>
#include <iostream>

template <typename T, size_t x, size_t z>
struct Ragged : std::array<std::vector<std::array<T, z>>, x> {
  Ragged(size_t y) {
    for (auto &i : *this) {
      i.resize(y);
    }
  }
};

int main() {
  using R5y5 = Ragged<int, 5, 5>;

  R5y5 a(3), b(4), c(2);
  vector<R5y5> d{a, b, c};
  d[1][1][2][3] = 99; // checked at() calls supported for all dimensions, too

  for (auto const &d : D) {
    for (auto const &x : d) {
      std::cout << "[";
      for (auto const &y : x) {
        std::cout << "[";
        for (auto const &z : y) {
          std::cout << z << " ";
        }
        std::cout << "]";
      }
      std::cout << "]" << std::endl;
    }
    std::cout << std::endl;
  }
}

This gets you multidimensional operator[] access to d and its elements, and allows you to put whatever y-dimensioned array inside d you want to. Note that the 3-dimensional pseudo-arrays are no longer stored completely compactly, but in potentially growable 2-D slices.

#include <stdio.h>

int main(){
    int A[5][3][5], B[5][4][5], C[5][2][5];
    void *D[3];
    D[0]=&A;
    D[1]=&B;
    D[2]=&C;
    B[1][2][3] = 99;
    printf("%d\n", (*(int(*)[5][4][5])D[1])[1][2][3]);//99

    return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top