开发者

How to check a character array is null in objective C

How to check a character array is null in objective C?

char hName[255]; 
- (void)setHost {
     phent = gethostbyaddr((const char*)&haddr, sizeof(int), AF_INET);
     if(phent){  
     strncpy(hName,phent->h_name,255);                                      

}

-(void) getHost {
    NSString *str = [[NSString alloc] initWithBytes:tTemp.hName 
    length:sizeof(tTemp.hName) encoding:NSASCIIStringEncoding];
 }

I have a character array named hName[255]. I will开发者_如何学Python assign values to this array at some point of my project. Now i need to check if the hName[255] contains null value. i tried some methods. I get a string str from that array and check if it is equal to @""; It failed. Then i check the length of the string str. Even if the array contains no values it will return 255. How can i check the array contains null value. Any help? Thanks in advance!!


You might need to elaborate a bit on your question. For example, to just check if a pointer is null is pretty simple :

char *my_chars;

...

if (! my_chars)
  NSLog(@"Woo, my_chars is null");
else
  NSLog(@"my_chars is at 0x%08x", my_chars);

because null is just 0 :)


However, it doesn't look like that's your problem. you've created an array of characters like so

char my_chars[255];

so my_chars is not going to be null.

However, as outis says in his answer, you've just allocated it and not zeroed the contents so you have no idea what's in those 255 bytes! Out of the three options he suggests I'd personally go with this one :

char my_chars[255];
memset(my_chars, 0, sizeof(my_chars));

now, you have an array of 255 zeroes :) This is pretty easy to check to see if it's null :

if (0 == strlen(my_chars))
  NSLog(@"It's not null but it is an empty string!");
else
  NSLog(@"my_chars contains a valid string which is %i chars long", strlen(my_chars));

Hope that helps.

Sam


First thing, note that the word "null" is overloaded. You can have null pointers and null (empty) strings, and there's the null character ('\0', equal to 0 when converted to an int:((int)'\0') == 0). There are also uninitialized variables, which may or may not be null. I'm guessing you're talking about an uninitialized character array, used as a c-string.

Most likely, hName is being allocated on the stack (I can't tell without seeing more of the source code), which means it's not zero-initialized. Practically speaking, hName will hold whatever data was last stored in the region of memory that hName occupies. You'll need to initialize it yourself.

char hName[255] = {0};
// or
memset(hName, 0, sizeof(hName));
// or, if you have bzero
bzero(hName, sizeof(hName));

Also note that since hName is declared as an array rather than a pointer, sizeof(hName) is the number of characters it stores.

void test() {
    char *name1 = "";
    char name2[255];
    // All the following lines will be true
    strlen(name1) == 0;
    sizeof(name2) == 255
    0 <= strlen(name2) && strlen(name2) < 255;
    // pointers are 4 or 8 bytes on most machines these days
    sizeof(name1) == 4 || sizeof(name1) == 8;
}

Edit (addressing code sample):

The length of str in getHost is 255 because you tell it to have that length when you copy from tTemp.hName. NSStrings can contain nulls, though you may have difficulty printing them and any characters following.

It's not clear from the code sample if hName is a global (globals are bad) or a property. Similarly, the scope of the other variables, such as haddr and tTemp, is unclear. Some of those should be parameters to the methods.

The name "setHost" should be reserved for a setter–one of a pair of methods ("accessors", in Objective-C parlance) that get and set a property. They return and take (respectively) a type that's notionally the type of the property. In this case, NSString* makes the most sense; best to use an NSString in your code and switch to (via NSString's cStringUsingEncoding: or UTF8String). The partner to -(void)setHost:(NSString*) would be -(NSString*)host.

Once you make the switch to NSString (and use stringFromCString:withEncoding:), you can simply examine its length or compare it to @"" to check for an empty string.

@interface MyHost : NSObject {
    NSString *name_;
    ...
}
/* post ObjC 2.0 */
@property(retain) NSString* name;
/* pre ObjC 2.0 */
-(NSString*)name;
-(void)setName:(NSString*);

/* any ObjC version */
-(int)setHostFromAddress:(MyAddress*)addr;
...
@end

@implementation MyHost
/* post ObjC 2.0 */
@synthesize name = name_;
-(int)setHostFromAddress:(MyAddress*)addr {
    struct hostent *phost;
    phost = gethostbyaddr(addr.address, addr.length, addr.type);
    if (phost) {
        self.name = [NSString stringWithCString:phost->h_hname encoding:NSASCIIStringEncoding];
    }
    return h_errno;
}

/* pre ObjC 2.0 */
-(NSString*)name {
    return name_;
}
-(NSString*)setName:(NSString*)nom {
    [name_ release];
    name_ = [nom retain];
}
-(int)setHostFromAddress:(MyAddress*)addr {
    struct hostent *phost;
    phost = gethostbyaddr([addr address], [addr length], [addr type]);
    if (phost) {
        [self setName:[NSString stringWithCString:phost->h_hname  encoding:NSASCIIStringEncoding]];
    }
    return h_errno;
}
...
@end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜