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

前端 未结 9 1797
庸人自扰
庸人自扰 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:09

    Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

    double (*A)[n] = malloc(sizeof(double[n][n]));
    

    and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

    free(A);
    

    Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

提交回复
热议问题