objective c - How to convert an array of NSString to an array of c-strings? -


i have nsarray<nsstring*>* object, , need invoke c api takes in array of strings char**.

what's best way this? important note c-strings must not have const modifier, following isn't enough since utf8string returns const char*:

nsarray<nsstring*>* names = ...; int len = args.count; char* cnames[len]; for( int = 0; < len; i++ ) {     cnames[i] = names[i].utf8string; }; 

you want dynamic memory cannot rely on backing memory utf8string being released.

nsarray *strings = @[ @"string 1", @"other string", @"random string"]; char **cstrings = null; nsinteger numcstrings = strings.count;  if (numcstrings) {     cstrings = (char **)calloc(numcstrings, sizeof(char*))  ;      if (cstrings) {         // safer allocate memory each string          (nsinteger i=0;i<numcstrings;i++) {             nsstring *nsstring = strings[i];             char *cstring = (char *)malloc([nsstring lengthofbytesusingencoding:nsutf8stringencoding] + 1); // + 1 \0              if (cstring) {                 strcpy(cstring, nsstring.utf8string);                 cstrings[i] = cstring;             } else {                 // should handle error             }         }     } else {         // should handle error     } }  (nsinteger i=0;i<numcstrings;i++) {     nslog(@"c-string (%ld): %s", i, cstrings[i]); }  // note need free memory later! // additional setup after loading view, typically nib. (nsinteger i=0;i<numcstrings;i++) {     if (cstrings[i]) {         // free each string         free(cstrings[i]);     } }  // free array free(cstrings);  cstrings = null; numcstrings = 0; 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -