How do I allocate a 2 D array with contigious memory ? How Do I use it to access rows and columns? Give me an example

后端 未结 4 1187
一向
一向 2020-12-21 09:09

I have created a 2 d array which reads as follows

     int i,j,lx,ly;// lx,ly are the row and column respectively
     double** a;

     a=(double**) malloc(         


        
4条回答
  •  抹茶落季
    2020-12-21 09:44

    Your approach is definitely heading in the right general direction.

    I think this:

    a=(double**) malloc((lx+2)*sizeof(double));
    

    would normally be:

    a = malloc(lx * sizeof(double *));
    

    And then without the contiguity requirement, this:

    a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));
    

    in most programs would look like:

    a[0] = malloc(ly * sizeof(double));
    

    And finally, that last line needs to be in a loop that assigns each a[i] with it's own malloc'ed space.

    However, that won't create contiguous memory. To do that you will need to do that big allocation and then divide it up for the row vector. So, instead of the second malloc in a loop, perhaps something like:

    double *t = malloc(lx * ly * sizeof(double));
    for (i = 0; i < lx; ++i)
        a[i] = t + i * ly;
    

    Putting it all together:

    #include 
    #include 
    
    void arrayDemo(int lx, int ly)
    {
      double **a;
      int i, j;
    
      a = malloc(lx * sizeof(double *));
      double *t = malloc(lx * ly * sizeof(double));
      for(i = 0; i < lx; ++i)
        a[i] = t + i * ly;
    
      for(i = 0; i < lx; ++i)
        for(j = 0; j < ly; ++j)
          a[i][j] = i*100 + j;
      for(i = 0; i < lx; ++i) {
        for(j = 0; j < ly; ++j)
          printf(" %4.0f", a[i][j]);
        printf("\n");
      }
    }
    
    int main(int ac, char **av)
    {
      arrayDemo(atoi(av[1]), atoi(av[2]));
      return 0;
    }
    
    $ cc -Wall all.c
    $ ./a.out 4 7
        0    1    2    3    4    5    6
      100  101  102  103  104  105  106
      200  201  202  203  204  205  206
      300  301  302  303  304  305  306
    

提交回复
热议问题