谁能解释一下如何从函数返回 C 中的二维数组?
我是 C 新手,在学习过程中我想从函数返回一个二维数组,以便我可以在我的主程序中使用它。谁能用例子向我解释一下。提前致谢。
I am new to C and during my learning I want to return a two dimensional array from a function, so that I can use it in my main program. Can anyone explain me the same with example. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于它如何实施。您可以仅使用一个一维数组,其中您知道每行(行)的长度,并且下一行紧接着上一行开始。或者,您可以有一个指向数组的指针数组。不过,额外的成本是您需要取消引用两个指针才能获取一个数据元素。
It depends how it is implemented. You can either work with just a one-dimensional array where you know the length of each (row) and the next row begins immediately after the previous one. OR, you can have an array of pointers to arrays. The extra cost though is you need to de-reference two pointers to get to one element of data.
将您的函数声明为返回一个指向指针的指针。如果我们使用 int 为例:
Declare your function as returning a pointer to a pointer. If we use int as an example:
以下是如何创建、操作和释放“二维数组”的示例:
要创建“二维数组”/矩阵,您所要做的就是创建一个动态指针数组(在此示例中) case
int*
) 的行/宽度的大小:然后将每个指针设置为指向列/高度的大小的
int
的动态数组:请注意,强制转换
malloc
不是必需的,这只是我的一个习惯。Here's an example of how you might create, manipulate and free a "2d array":
To create a "2d array"/matrix, all you have to do is create a dynamic array of pointers (in this case
int*
) of the size of the rows/width:Then you set each of those pointers to point to a dynamic array of
int
of the size of the columns/height:Note that the casts on
malloc
aren't required, it's just a habit I have.