如何在C ++中返回本地数组? [英] How to return local array in C++?

查看:176
本文介绍了如何在C ++中返回本地数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  char * recvmsg(){
char buffer [1024];
return buffer;
}

int main(){
char * reply = recvmsg();
.....
}

我收到警告: p>


警告C4172:返回局部变量或临时变量的地址



解决方案

您需要动态分配您的字符数组:

  char * recvmsg ){
char * buffer = new char [1024];
return buffer;
}

用于C ++和

  char * recvmsg(){
char * buffer = malloc(1024);
return buffer;
}



<发生什么是,没有动态分配,你的变量将驻留在函数的堆栈,因此会在退出时被销毁。这就是为什么你得到警告。在堆上分配它防止了这一点,但是你必须小心,并通过 delete [] 释放内存。


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

解决方案

You need to dynamically allocate your char array:

char *recvmsg(){
   char* buffer = new char[1024];
   return buffer;
}

for C++ and

char *recvmsg(){
   char* buffer = malloc(1024);
   return buffer;
}

for 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[].

这篇关于如何在C ++中返回本地数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆