How to return local array in C++?(如何在 C++ 中返回本地数组?)
问题描述
char *recvmsg(){
char buffer[1024];
return buffer;
}
int main(){
char *reply = recvmsg();
.....
}
我收到警告:
警告 C4172:返回局部变量或临时地址
warning C4172: returning address of local variable or temporary
推荐答案
你需要动态分配你的char数组:
You need to dynamically allocate your char array:
char *recvmsg(){
char* buffer = new char[1024];
return buffer;
}
对于 C++ 和
char *recvmsg(){
char* buffer = malloc(1024);
return buffer;
}
对于 C.
如果没有动态分配,您的变量将驻留在函数的堆栈中,因此会在退出时被销毁.这就是你收到警告的原因.在堆上分配它可以防止这种情况发生,但是您必须小心并通过 delete[] 完成后释放内存.
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[].
这篇关于如何在 C++ 中返回本地数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中返回本地数组?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
