Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get the error "Array initializer must be an initializer list" when I'm trying to return this array in a function?

I am coming from Java, and I'm very new to Objective C. Anyway, I have this static method which is designed to make a copy of an array (if there's a better way to accomplish this, please let me know, but I'm asking this question more-so to find out why I got this error and how to avoid such an error in the future.) I ran into some problems with it, but just when I thought I had them all sorted out, I got this error that looked like XCode

Here is the method in the interface:

+ (float[]) copyArray: (float[]) array withLength: (int) length;

And here is the method in the implementation:

+ (float[]) copyArray: (float[]) array withLength: (int) length
{
    float copiedArray[length];
    for (int i = 0; i < length; i++)
    {
        copiedArray[i] = array[i];
    }
    return copiedArray;
}
like image 594
michaelsnowden Avatar asked Jan 05 '14 21:01

michaelsnowden


2 Answers

C arrays are way more tricky than Java arrays. One of the biggest issues is that in a lot of instances, you don't know how large a C array is unless you have saved this information in a different variable, for example. The C FAQ "Arrays and Pointers" lists a lot of traps and they apply to Objective-C as well. You might want to see question 6.5 in particular.

As @lwxted already suggested, try to avoid C arrays unless you really know what you're doing and you have determined that you need them. C arrays are faster than NSArray but unless you have determined that your array really is a performance bottleneck by measuring with a profiler you will most likely not notice any difference.

And I strongly recommend avoiding a C array of Objective-C objects (id objects[]) unless you really, really know very well what you are doing (memory management issues).

like image 109
DarkDust Avatar answered Nov 08 '22 19:11

DarkDust


method/function cannot return C array. you should do this

+ (void) copyArrayFrom:(float *)array to:(float *)toArray withLength: (unsigned) length
{
    for (int i = 0; i < length; i++)
    {
        toArray [i] = array[i];
    }
}
like image 38
Bryan Chen Avatar answered Nov 08 '22 19:11

Bryan Chen