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; //
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; //
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.
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.