如何在 C 中正确设置、访问和释放多维数组? [英] How do I correctly set up, access, and free a multidimensional array in C?

查看:32
本文介绍了如何在 C 中正确设置、访问和释放多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 C 中的多维数组,我已经看到了许多关于我的代码有什么问题"的问题.出于某种原因,人们似乎无法理解这里发生的事情,所以我决定回答这个问题作为参考他人:

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 happening here, so I decided to answer this question as a reference to others:

如何在 C 中正确设置、访问和释放多维数组?

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

如果其他人有有用的建议,请随时发布!

If others have helpful advice, please feel free to post along!

推荐答案

在 C99 之后的 C 中,即使是动态多维数组也可以通过 malloc 一次性轻松分配,并通过 free<释放/代码>:

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);

这篇关于如何在 C 中正确设置、访问和释放多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆