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 1143
一向
一向 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:46

    This code allocates a 10 by 5 contiguous block of memory, initializes it with incrementing doubles, and then prints the values indexed by x and y:

    #include "2d.h"
    
    int main(void){
    
        unsigned int x,y;
        const unsigned int width = 10;
        const unsigned int height = 5;
    
        //we need an index into the x of the array
        double * index[width];
    
        //need the memory to store the doubles
        unsigned int memorySizeInDoubles = width * height;
        double * memory = malloc(memorySizeInDoubles * sizeof(double));
    
        //initialize the memory with incrementing values
        for(x = 0; x < memorySizeInDoubles; ++x){
            memory[x] = (double) x;
        }
    
        //initialize the index into the memory
        for(x = 0; x < width; ++x){
            index[x] = memory + height * x;
        }
    
        //print out how we did
        for(x = 0; x < width; ++x){
            for(y = 0; y < height; ++y){
               printf("[%u, %u]: Value = %f\n", x, y, index[x][y]);
            }
        }
    
        free(memory);
    
        return 0;
    }
    

    The 2d.h file should contain these lines:

    #include 
    #include 
    
    int main(void);
    

    Note: The memory created is only contiguous for some definitions. The memory is logically contiguous, but not necessarily physically contiguous. If this memory is for a device driver for instance, malloc won't work.

提交回复
热议问题