返回数组(警告:函数返回局部变量的地址)? [英] Returning an array (Warning: Function returns address of local variable)?

查看:422
本文介绍了返回数组(警告:函数返回局部变量的地址)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回数组(警告:函数返回局部变量的地址)

Returning an array (Warning: Function returns address of local variable) ?

interface

interface

int* decimalConversion(int iX);






实施


implementation

int* decimalConversion(int iX){
    int iMult[10] = {0,0,0,0,0,0,0};

    ...

    return iMult;  // <-- Warning: Function returns address of local variable
}


推荐答案

你应该为数组分配空间,如果你在该函数中使用C,则返回在堆栈上创建的数组的地址(因此局部变量警告)use malloc(my_arr_size )如果不使用obj-c的alloc。

You should allocate space for the array, you're returning the address of an array that was created on the stack (hence local variable warning) if you're using C in that function use malloc(my_arr_size) if not use obj-c's alloc.

例如:

int *my_arr = calloc(10, sizeof(int)); //make sure we get zeroed memory
//fill array
return my_arr; //should no longer give a warning

完成后只需使用free(my_arr) 。原因我在C中是这样做的,因为我可以看到你返回一个int *类型和使用C风格的声明,所以如果你在Obj-c让我知道,我可以改变我的答案的例子。

When done with it just use free(my_arr) same as release. Reason I did this in C is because I can see that you're returning an int* type and using C style declarations so if you're doing it in Obj-c let me know and I can change my answer's example.

得到这个错误的原因是因为局部数组放在堆栈上,当你返回一个堆栈帧中返回一个地址的数组。问题是,当该方法完成执行时,堆栈框架不再有效,因此您不能指望该框架上的任何数据是有效的(虽然有些情况下,这种方法可行,但被认为是不好的做法)。通过在堆上分配该数组,您可以返回一个堆地址,在那里您的数据确实存在,直到您对该数据的指针调用free()。​​

The reason you are getting this error is because local arrays get put on the stack, when you return that array you return an address in a stack frame. The problem is that when that method finishes execution that stack frame is no longer valid and therefore you cannot expect any data that was on that frame to be valid (although there are cases when this does work but it is considered bad practice). By allocating that array on the heap you can return a heap address where your data is assured to exist until you call free() on the pointer to that data.

这篇关于返回数组(警告:函数返回局部变量的地址)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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