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 1178
一向
一向 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:50

    In C, to have one chunk of contiguous memory, you need one malloc(), or have a statically allocated array. Since you want dynamic memory, you will need malloc(). Since you need everything to be contiguous, you will need only one call to it.

    Now, what should the call look like? If I understood you correctly, you need lx times ly values, each with size sizeof(double), so you need lx*ly*sizeof(double) bytes to be allocated.

    Digression: I prefer writing my malloc() calls as follows:

    #include  /* for malloc's prototype */
    T *pt; /* for any type T */
    size_t n; /* need n objects of type T */
    
    pt = malloc(n * sizeof *pt);
    

    Using sizeof with sizeof *pt instead of sizeof(T) offers an advantage that if the type of pt changes, you don't need to change the malloc() call. Not casting the result of malloc() is nice because then the whole malloc() call is type-agnostic, and is easier to type and read. Be sure to #include though.

    So, to allocate space for n doubles, you can do:

    double *pd = malloc(n * sizeof *pd);
    if (pd != NULL) {
        /* malloc succeeded */
    } else {
        /* malloc failed */
    }
    

    Now, after allocating memory, you need to be able to index it. Let's say you have lx == 2 and ly == 3. Your memory looks like:

        +---+---+---+---+---+---+
    pd: | 0 | 1 | 2 | 3 | 4 | 5 |
        +---+---+---+---+---+---+
    

    pd[0], pd[1] and pd[2] are the double values corresponding to the first row, pd[3] to pd[6] are the double values corresponding to the second row. You should be able to generalize this observation to translate a given x,y index pair to one number that indexes into your pd array properly.

提交回复
热议问题