开发者

Function returning an array in ObjC for iPhone

开发者 https://www.devze.com 2023-02-10 23:54 出处:网络
Hello I am trying to make this function to return an array! What is going wrong here? -(char[10])print01:(int)int11{ //error: declared as method returning开发者_开发技巧 an array

Hello I am trying to make this function to return an array! What is going wrong here?

-(char[10])print01:(int)int11{ //error: declared as method returning开发者_开发技巧 an array
    char arrayT[10];

    for(int i=0;i<8;i++)
    {
        if ((int1-n1)>=0){
            arrayT[i]='1';
            int1-=n1;
        }
        else 
            arrayT[i]= '0';
        n1=n1/2;
    }

    return arrayT[]; // incompatible types in return
}

and I want to call it like that:

char array1[10] = [self print01:(int)int1]; //error: invalid initializer

any suggestions please?


You can't return an array in C or in Objective-C. The best you can hope for is to return a pointer to an array, but if you're going to do that, make sure you don't return a pointer to an array on the stack (like yours is).


The best approach is using an NSArray (of objects of course, I'm assuming the above code is simplified sample, but you can always use an NSNumber). Alternatively, you could return a pointer to an array, which is common in C as C (and objective c by extension) cannot return an array. Unfortunately, this would require allocating memory for the array and using manual memory management, (malloc/free) which depending on the lifecycle of the array, can be anywhere from a nuisance to awful. My recommendation is taking a char *dest parameter, and inserting chars into the array as dest[i]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号