开发者

NSString to char[] in Objective-c

I have to convert a NSString to a null en开发者_Python百科ded char[].

The way Im doing it is like this:

NSString *regC = @"1234"    
char REG[[regC length] +1];
BOOL result = [regC getCString:REG maxLength:32 encoding:NSUTF8StringEncoding];

and I dont know if is it the correct way.

REG has to be a 5 chars array, with a null in the last one/

Thanks.


char *REG = [@"test" UTF8String];

You can't allocate the length of a char[] at runtime unless you use malloc/free. but with the above way you won't need to manage memory.


This is the correct way to convert as long as you use ASCII characters in your NSString. They are representer as single byte characters in UTF-8 encoding. If you use some non-ASCII characters you should make your REG bigger.

Upd: one more: you should put your actual buffer size into "maxLength:" parameter in order to avoid buffer overrun. Not 32 but [regC length] +1.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜