Morpheus
Morpheus

Reputation: 3523

How to check for null strings in a C array

I have a C array declared like char* arrayOfVarNames[3];

This array is populated by some api and the strings in this array are again used by an objective-C method.

I want to know if there are any null strings in the arrayOfVarNames[3] before passing to the objective-C method. NSString *tempString = [NSString stringWithCString:arrayOfVarNames[i] encoding:NSUTF8StringEncoding]; Anyway to check for null strings?

Upvotes: 0

Views: 80

Answers (3)

Deduplicator
Deduplicator

Reputation: 45654

Depending on what you mean with a null string, you test for:

  • The pointer being NULL: !p
  • The pointer pointing to an empty string: !*p

Beware that some interfaces handle those cases as interchangeable, so that you must accept both as an empty string.

Upvotes: 0

Cy-4AH
Cy-4AH

Reputation: 4585

One line code solution:

NSString *tempString = NULL == arrayOfVarNames[i] ? nil : [NSString stringWithCString:arrayOfVarNames[i] encoding:NSUTF8StringEncoding];

Upvotes: 0

rmaddy
rmaddy

Reputation: 318804

A simple if statement:

NSString *tempString = nil;
if (arrayOfVarNames[i]) {
    // It's not NULL
    tempString = [NSString stringWithCString:arrayOfVarNames[i] encoding:NSUTF8StringEncoding];
} else {
    tempString = @""; // or some other appropriate action
}

Upvotes: 2

Related Questions