dynamic allocating array of arrays in C

后端 未结 7 891
南笙
南笙 2020-11-30 04:08

I don\'t truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:

int **m;

in order to decla

7条回答
  •  -上瘾入骨i
    2020-11-30 04:43

    Humm. How about old fashion smoke and mirrors as an option?

    #define ROWS  5
    #define COLS 13
    #define X(R, C) *(p + ((R) * ROWS) + (C))
    
    int main(void)
    {
        int *p = (int *) malloc (ROWS * COLS * sizeof(int));
        if (p != NULL)
        {
            size_t r;
            size_t c;
            for (r = 0; r < ROWS; r++)
            {
                for (c = 0; c < COLS; c++)
                {
                     X(r,c) = r * c;  /* put some silly value in that position */ 
                }
            }
    
            /* Then show the contents of the array */ 
            for (r = 0; r < ROWS; r++)
            {
                printf("%d ", r);   /* Show the row number */ 
    
                for (c = 0; c < COLS; c++)
                {
                     printf("%d", X(r,c));
                }
    
                printf("\n");
            }
    
            free(p);
        }
        else
        {
            /* issue some silly error message */ 
        }
    
        return 0;
    }
    

提交回复
热议问题