How can I work with dynamically-allocated arbitrary-dimensional arrays?

前端 未结 3 1598
死守一世寂寞
死守一世寂寞 2020-11-30 15:16

The typical 1-D array can be statically or automatically allocated in a declaration.

enum { n=100 };
int arr1[n];

Or dynamically-allocated

3条回答
  •  粉色の甜心
    2020-11-30 15:56

    If you define a as a pointer to an array of n integers, the compiler will do the index arithmetic.

    #define N 7
    int (*a)[N];
    
    int main() {
      a = malloc(N*N*sizeof(int));
      a[2][3] = 0;
    }
    

    ADDED:

    Similarly, a three dimensional example:

    #include 
    #include 
    
    #define N 7
    
    int (*a)[N][N];
    
    int main() {
        int i,j,k;
        a = malloc(N*N*N*sizeof(int));
        for(i=0; i

提交回复
热议问题