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

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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

interface

int* decimalConversion(int iX); 

implementation

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

回答1:

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.

Example:

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

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.

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.



回答2:

If you are doing this for an app written in Objective-C, I would suggest using NSArray. NSArray is an Objective-C class for immutable arrays, and doesn't require that you manually allocate memory. The only turnoff is that you have to encapsulate your integers in NSNumber objects. An example would be:

NSArray * getNums (int num) {     NSArray * result = [NSArray arrayWithObjects:[NSNumber numberWithInt:num-1], [NSNumber numberWithInt:num], [NSNumber numberWithInt:num+1], nil];     return result; } ... NSArray * myList = getNums(10); NSLog(@"First: %d", [[myList objectAtIndex:0] intValue]); NSLog(@"Second: %d", [[myList objectAtIndex:1] intValue]); NSLog(@"Third: %d", [[myList objectAtIndex:2] intValue]); 

You can alternatively do this:

NSArray * getNums (int num) {     NSMutableArray * array = [NSMutableArray array];     [array addObject:[NSNumber numberWithInt:num-1]];     [array addObject:[NSNumber numberWithInt:num]];     [array addObject:[NSNumber numberWithInt:num+1]];     return array; } ... NSArray * myList = getNums(10); for (int i = 0; i 

The only difference is that NSMutableArray allows you to add/remove elements after the fact.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!