How do I correctly set up, access, and free a multidimensional array in C?

后端 未结 5 955
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:31

I have seen dozens of questions about “what’s wrong with my code” regarding multidimensional arrays in C. For some reason people can’t seem to wrap their head around what is

5条回答
  •  隐瞒了意图╮
    2020-11-21 23:48

    In C since C99, even dynamic multidimensional arrays can be easily allocated in one go with malloc and freed with free:

    double (*A)[n] = malloc(sizeof(double[n][n]));
    
    for (size_t i = 0; i < n; ++i)
      for (size_t j = 0; j < n; ++j)
          A[i][j] = someinvolvedfunction(i, j);
    
    free(A);
    

提交回复
热议问题