Basically I have a class method that returns a float array. If I return a static array I have the problem of it being too large or possibly even too small depending on the input parameter as the size of the array needed depends on the input size. If I return just a float array[arraysize] I have the size problem solved but I have other problems.
Say for example I address each element of the non-static float array individually e.g.
NSLog(@"array[0] %f array[1] %f array[2] %f",array[0],array[1],array[2]);
It prints the correct values for the array. However if I instead use a loop e.g.
for (int i = 0; i < 3; i++)
{
NSLog(@"array[%i] %f",i,array[i]);
}
I get some very strange numbers (apart from the last index, oddly). Why do these two things produce different results? I’m aware that its bad practice to simply return a non static float, but even so, these two means of addressing the array look the same to me.
Relevant code from class method (for non-static version)…
float array[arraysize];
//many lines of code later
if (weShouldStoreValue == true) {
array[index] = theFloat;
index = index + 1;
}
//more lines of code later
return array;
Note that it returns a (float*).
You can’t do that, array dies when you exit from the method or function scope.
You can do this using malloc in plain C:
Don’t forget to free the memory associated.
If you got habit to use the garbage collector and to con’t care about the memory, wrap the malloc’s data into a NSData object so that it will be freed, allocating with a method like this one:
But at this point why not using a NSMutableArray of numbers?