How do I work with dynamic multi-dimensional arrays in C?

前端 未结 9 1737
庸人自扰
庸人自扰 2020-11-22 05:14

Does someone know how I can use dynamically allocated multi-dimensional arrays using C? Is that possible?

9条回答
  •  野性不改
    2020-11-22 06:06

    If you know the number of columns at compile time, it's pretty simple:

    #define COLS ...
    ...
    size_t rows;
    // get number of rows
    T (*ap)[COLS] = malloc(sizeof *ap * rows); // ap is a *pointer to an array* of T
    

    You can treat ap like any 2D array:

    ap[i][j] = x;
    

    When you're done you deallocate it as

    free(ap);
    

    If you don't know the number of columns at compile time, but you're working with a C99 compiler or a C2011 compiler that supports variable-length arrays, it's still pretty simple:

    size_t rows;
    size_t cols;
    // get rows and cols
    T (*ap)[cols] = malloc(sizeof *ap * rows);
    ...
    ap[i][j] = x;
    ...
    free(ap);
    

    If you don't know the number of columns at compile time and you're working with a version of C that doesn't support variable-length arrays, then you'll need to do something different. If you need all of the elements to be allocated in a contiguous chunk (like a regular array), then you can allocate the memory as a 1D array, and compute a 1D offset:

    size_t rows, cols;
    // get rows and columns
    T *ap = malloc(sizeof *ap * rows * cols);
    ...
    ap[i * rows + j] = x;
    ...
    free(ap);
    

    If you don't need the memory to be contiguous, you can follow a two-step allocation method:

    size_t rows, cols;
    // get rows and cols
    T **ap = malloc(sizeof *ap * rows);
    if (ap)
    {
      size_t i = 0;
      for (i = 0; i < cols; i++)
      {
        ap[i] = malloc(sizeof *ap[i] * cols);
      }
    }
    
    ap[i][j] = x;
    

    Since allocation was a two-step process, deallocation also needs to be a two-step process:

    for (i = 0; i < cols; i++)
      free(ap[i]);
    free(ap);
    

提交回复
热议问题