17
const char arr[]="Hello There";

I am trying to create a character array as above.

Below, is the code which I use. Is this a correct way to create a char array.

-(void) createCharArray:(NSString*) text{
   char arr[text.length];
   for(int i=0;i<text.length;i++){
    arr[i]=[text characterAtIndex:i];
   }
}

Do we have to worry about null termination? Do we have any other way to achieve the same?

Undo
  • 25,519
  • 37
  • 106
  • 129
NNikN
  • 3,720
  • 6
  • 44
  • 86
  • Simple: `const char arr[]="Hello There";`. Of course, if you want to create a char array *from an NSString* then maybe you'd want to look at the spec for NSString and pick one of the several methods it provides. – Hot Licks Feb 19 '14 at 03:10

3 Answers3

37

You can use UTF8String. Eg: [myString UTF8String].

Pranav
  • 680
  • 6
  • 11
  • 1
    I think UTF8String returns a character array pointer – NNikN Feb 19 '14 at 03:06
  • 1
    It returns a `char*` which you can use like you would use a `char[]`. – Pranav Feb 19 '14 at 03:10
  • 2
    As always with C, "array" is a nebulous term. – Hot Licks Feb 19 '14 at 03:11
  • char c[]=[text UTF8String]; throws a error "Array initialiser must be an initialiser list to string literal" – NNikN Feb 19 '14 at 03:15
  • 4
    So use char *c = [text UTF8String]; You want a pointer to a dynamically allocated buffer of characters, not a statically created C string. – Duncan C Feb 19 '14 at 03:20
  • That's right, I forgot about the UTF8String convenience method. That's easier than my suggestion to use getCString:maxLength:encoding with an encoding of NSUTF8StringEncoding. (Voted) – Duncan C Feb 19 '14 at 03:21
3

No, that is not the correct way on several levels. NSString supports unicode, which far exceeds the number of possible characters that will fit in a byte array.

You need to use an encoding like UTF8 if yo want to convert unicode to 8 bit characters.

Take a look at the method getCString:maxLength:encoding:, and try using NSUTF8StringEncoding.

That method should do what you want to do with a single call.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
3

Use,

NSString *str = @"Hello There";
const char *c = [str cStringUsingEncoding:NSUTF8StringEncoding];
Akhilrajtr
  • 5,170
  • 3
  • 19
  • 30