You cannot return the local array C. You need malloc(sizeof(UInt8) * 4) , fill it in, return the pointer, and, of course, remember to free it when you are done.
Here is an example of how it will be written and used (just to emphasize the importance of freeing allocated memory):
+ (UInt8 *)convertToBytes:(int)i { UInt8 *retVal = malloc(sizeof(UInt8) * 4); retVal[0] = i >> 24; retVal[1] = i >> 16; retVal[2] = i >> 8; retVal[3] = i >> 0; return retVal; } - (void)someMethodUsingTheOtherOne { int something = 900; UInt8 *bytesOfInt = [[self class] convertToBytes:something]; someFunctionUsingTheBytes(bytesOFInt); free(bytesOfInt); }
(You will probably notice that I also changed it as a class method. Since it does not depend on any instance attributes, it is more reasonable for it to use a class method or even a function. But this has nothing to do with how arrays work and pointers - I just like to use a good coding style in the examples.)
Chuck source share