C ++ - 通过函数返回一个二维数组 [英] C++ - Returning a 2D array through function
问题描述
我有一些回答说:
无,因为数据是函数的本地,当它返回时,数组指向垃圾数据(因为它可以随时被覆盖)。但是,有些人说是的,像正常数组一样返回。
我有一个二维数组,指向 Tile
objects
Tile * map [128] [128];
?为什么或者为什么不?如果答案是肯定的,我该怎么办?
编辑:我不清楚。我想创建一个getter方法来返回map变量,并且能够在另一个函数中使用数组中的指针。
你可以这样做...问题是,你的调用者现在负责释放内存。他可能不知道你是如何分配的。他应该调用free()吗?删除[]?由操作系统提供的自由例程?
这两种常见的方法是:
- 让调用者分配内存,你的函数只是填充它
- 使用C ++数组类;这里你可能有一个std :: vector包含一个std :: vector的Tile *。这是伟大的,因为它解决你手动处理内存分配/释放。
但是...谁将释放Tile *实例?和什么API?所以也许你需要一个Tile的向量向量,而不是Tile *。
vector< vector< Tile>地图;
I've looked around trying to figure out if I should return a 2D array in C++, but got mixed answers.
Some of the answers say no because the data is local to the function and when it returns, the array points to "junk data" (as it can be overwritten at any time). However, some said "yes, return it like a normal array."
So, to my dilemma:
I have a 2D array that holds pointers to Tile
objects
Tile* map[128][128];
Should I return the array in a function? Why or why not? If the answer is yes, how would I do that?
EDIT: I was unclear. I want to make a getter method to return the map variable and be able to use the pointers in the array in another function.
You could do that... the problem is that your caller is now responsible for freeing the memory. And he might not know how you allocated it. Should he call free()? delete[]? A free routine provided by the OS? Or one provided by some other memory caching system in your app?
Two common ways around this are:
- Have the caller allocate the memory and your function merely populates it
- Use a C++ array class; here you might have a std::vector containing a std::vector of Tile*. This is great as it absolves you of manually dealing with the memory allocation/deallocation.
But then... who's going to free the Tile* instances? And with what API? So perhaps you need a vector of vectors of Tile, rather than Tile*.
vector<vector<Tile>> map;
这篇关于C ++ - 通过函数返回一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!