C-函数返回2D数组 [英] C - Function return 2D array
问题描述
也许我的问题很简单,但是我是C语言的新人.
Maybe my question is easy but I am newby in C.
我创建了一个函数,该函数从文件中读取一些数据,然后将其传递给另一个函数,该函数解析给定行数和列数并创建2D数组.
I create a function which read some data from a file and then pass them to a another function which parse them given number of rows and columns and create a 2D array.
我想返回此数组以便在其行中执行一些操作.如何在C中返回2D数组
I want to return this array in order to perform some operantions in its rows. How can I return a 2D array in C
有人可以给我一个例子吗,或者我做错了什么?
Can someone give me an example or what may I did wrong?
致谢
推荐答案
请注意,用C返回数组是初学者的陷阱,因为它高度依赖于存储时间:
Beware, returning arrays in C is a beginner's trap, because it is highly dependant on the storage duration:
- 静态或全局:没问题,但是下次调用会覆盖内容
- 自动:从不这样做!实际上返回的是一个悬挂指针,因为数组的寿命在return语句的结尾处结束
- dynamic(malloc-ed):很好,但是调用方必须稍后将其释放.
- static or global: no problem, but content will be overwritten by next call
- automatic : never do that! What is actually returned is a dangling pointer, because the array's life ends at the end of the return statement
- dynamic (malloc-ed): fine, but caller must free it later.
一种更惯用的方法是,调用方传递它拥有的数组及其大小.
An more idiomatic way is that the caller passes an array that it owns, along with its size(s).
这篇关于C-函数返回2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!