Array of pointers to an array of fixed size

后端 未结 9 1759
心在旅途
心在旅途 2020-12-14 06:04

I tried to assign two fixed-size arrays to an array of pointers to them, but the compiler warns me and I don\'t understand why.

int A[5][5];
int B[5][5];
int         


        
9条回答
  •  醉梦人生
    2020-12-14 06:28

    I am a great believer in using typedef:

    #define SIZE 5
    
    typedef int  OneD[SIZE]; // OneD is a one-dimensional array of ints
    typedef OneD TwoD[SIZE]; // TwoD is a one-dimensional array of OneD's
                             // So it's a two-dimensional array of ints!
    
    TwoD a;
    TwoD b;
    
    TwoD *c[] = { &a, &b, 0 }; // c is a one-dimensional array of pointers to TwoD's
                               // That does NOT make it a three-dimensional array!
    
    int main() {
        for (int i = 0; c[i] != 0; ++i) { // Test contents of c to not go too far!
            for (int j = 0; j < SIZE; ++j) {
                for (int k = 0; k < SIZE; ++k) {
    //              c[i][j][k] = 0;    // Error! This proves it's not a 3D array!
                    (*c[i])[j][k] = 0; // You need to dereference the entry in c first
                } // for
            } // for
        } // for
        return 0;
    } // main()
    

提交回复
热议问题