C++ 如何在C++中返回本地数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7769998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return local array in C++?
提问by Nawaz
char *recvmsg(){
char buffer[1024];
return buffer;
}
int main(){
char *reply = recvmsg();
.....
}
I get a warning:
我收到警告:
warning C4172: returning address of local variable or temporary
警告 C4172:返回局部变量或临时变量的地址
采纳答案by Luchian Grigore
You need to dynamically allocate your char array:
您需要动态分配您的字符数组:
char *recvmsg(){
char* buffer = new char[1024];
return buffer;
}
for C++ and
对于 C++ 和
char *recvmsg(){
char* buffer = malloc(1024);
return buffer;
}
for C.
对于 C。
What happens is, without dynamic allocation, your variable will reside on the function's stack and will therefore be destroyed on exit. That's why you get the warning. Allocating it on the heap prevents this, but you will have to be careful and free the memory once done with it via delete[]
.
发生的情况是,如果没有动态分配,您的变量将驻留在函数的堆栈中,因此将在退出时销毁。这就是您收到警告的原因。在堆上分配它可以防止这种情况,但是您必须小心并在通过delete[]
.
回答by Nawaz
I would suggest std::vector<char>
:
我建议std::vector<char>
:
std::vector<char> recvmsg()
{
std::vector<char> buffer(1024);
//..
return buffer;
}
int main()
{
std::vector<char> reply = recvmsg();
}
And then if you ever need char*
in your code, then you can use &reply[0]
anytime you want. For example,
然后,如果您需要char*
在代码中使用,那么您可以&reply[0]
随时使用。例如,
void f(const char* data, size_t size) {}
f(&reply[0], reply.size());
And you're done. That means, if you're using C API, then you can still use std::vector
, as you can pass &reply[0]
to the C API (as shown above), and reply
to C++ API.
你已经完成了。这意味着,如果您使用 C API,那么您仍然可以使用std::vector
,因为您可以传递&reply[0]
给 C API(如上所示)和reply
C++ API。
The bottomline is : avoid using new
as much as possible. If you use new
, then you've to manage it yourself, and you've to delete
when you don't need it.
底线是:new
尽可能避免使用。如果您使用new
,那么您必须自己管理它,并且delete
在您不需要它时必须这样做。
回答by Mysticial
The warning message is correct. You're returning the address of a local array which disappears after the function returns.
警告信息是正确的。您正在返回一个本地数组的地址,该地址在函数返回后消失。
You can do this using dynamic memory allocation:
您可以使用动态内存分配来做到这一点:
char *recvmsg(){
char *buffer = (char*)malloc(1024);
return buffer;
}
The catch is that you need to make sure you free()
the pointer later on to avoid a memory leak.
问题是您需要确保free()
稍后使用指针以避免内存泄漏。
Alternatively, you can pass the buffer into the function.
或者,您可以将缓冲区传递给函数。
void recvmsg(char *buffer,int buffer_size){
// write to buffer
}
void main(){
char buffer[1024];
recvmsg(buffer,1024);
}
This avoids the need for a memory allocation. This is actually the preferred way to do it.
这避免了对内存分配的需要。这实际上是执行此操作的首选方法。
回答by NPE
The problem is that buffer
lives on the stack and goes out of scope the moment you exit recvmsg
.
问题是它buffer
存在于堆栈中,并在您退出时超出范围recvmsg
。
You could allocate buffer
on the heap:
您可以buffer
在堆上分配:
char *recvmsg(){
char *buffer = malloc(1024);
return buffer;
}
Note that now the caller is responsibe for disposing of the allocated memory:
请注意,现在调用者负责处理分配的内存:
void main(){
char *reply = recvmsg();
free(reply);
}
回答by Lou Franco
You could dynamically create the buffer, but then the caller needs to know to free it.
您可以动态创建缓冲区,但是调用者需要知道释放它。
I think it's better to pass in a buffer (assuming recvmsg also fills it)
我认为最好传入一个缓冲区(假设 recvmsg 也填满了它)
void recvmsg(char *buffer, size_t size){
}
void main(){
char buffer[1024];
recvmsg(buffer, sizeof(buffer));
}
Even if the caller decides dynamic is better, they will know that they need to free it, and the specific way to do that (free(), delete, delete[], or perhaps something special from a custom allocator)
即使调用者认为动态更好,他们也会知道他们需要释放它,以及释放它的具体方法(free()、delete、delete[],或者可能是自定义分配器中的一些特殊东西)
回答by MGZero
You have a few options...The way you're doing it now is going to cause undefined behavior as the array will go out of scope once hte function returns. So one option is to dynamically allocate the memory..
你有几个选择......你现在做的方式会导致未定义的行为,因为一旦 hte 函数返回,数组就会超出范围。所以一种选择是动态分配内存..
char * recmsg()
{
char * array = new char[128];
return array;
}
Just remember to clean it up with delete this way (or free if you used malloc). Second, you could use a parameter...
只记得用这种方式删除清理它(或者如果你使用 malloc 则免费)。其次,您可以使用参数...
void recmsg(char * message, int size)
{
if (message == 0)
message = new char[size];
}
Again, the same thing goes for clean up here as with the previous. Also note the check for 0 to make sure you don't call new on a pointer that's been allocated already.
同样,这里的清理工作和之前的一样。还要注意检查 0 以确保您不会在已经分配的指针上调用 new 。
Last, you could use a vector..
最后,您可以使用向量..
std::vector<char> recmsg()
{
std::vector<char> temp;
//do stuff with vector here
return temp;
}
回答by Shubhankar Sisodia
char *recvmsg(){
char *buffer = new char;
cout<<"\nENTER NAME : ";
cin>> buffer;
return buffer;
}
int main(){
char *reply = recvmsg();
cout<<reply;
}
回答by Juergen
Just to complete the picture:
只是为了完成图片:
It is not necessary, to allocate memory with malloc. You can also create the buffer on the stack, but you must create it on a stack frame that lives as long as the consumer of the buffer lives. That was the error of the OP -- when the callee was finished, the buffer was deleted and the caller got a invalid pointer.
没有必要用 malloc 分配内存。您也可以在堆栈上创建缓冲区,但您必须在一个堆栈帧上创建它,该堆栈帧的生命周期与缓冲区的使用者存在时间一样长。那是 OP 的错误——当被调用者完成时,缓冲区被删除,调用者得到一个无效的指针。
So what you can do is this:
所以你可以做的是:
void recvmsg(char *buffer, size_t size) {
... do what you want ...
}
void main(void) {
char buffer[1024];
recvmsg(buffer, sizeof(buffer));
}
回答by karl
how about passing by ref
通过 ref 怎么样
char buf[1024];
PutStuffInBuff(&buf);
回答by Nitesh Narayan Lal
when you are returning the buffer then as it acting as a pointer to the first location of the array so it will return its address.And the place where you are calling the function there you can make a character pointer which will store this returned address value .After which you can move your pointer and can access all the elements of your array.
当您返回缓冲区时,因为它充当指向数组第一个位置的指针,因此它将返回其地址。在您调用函数的地方,您可以创建一个字符指针来存储此返回的地址值.之后您可以移动指针并可以访问数组的所有元素。