开发者

char pointers and the IF statement

I have a char pointer returned from a function, and i want to double check its value using the IF statement how should i implement this开发者_如何学JAVA one in C.

substring function from here

I want it something like this

if (substring("xxxNameYYY",0,3)=="xxx"){
     //do this
} else {
     //do that
}

the above if statement always go to "do that" part.

thanks


You cannot compare string like that in C, you have to use strcmp(str1, str2) == 0 to check if they are equal.

In your case:

char * substr = substring("xxxNameYYY",0,3);
if (strcmp(substr, "xxx") == 0) {
    /* TODO */
}
else {
    /* TODO */
}


Since this is a pointer, doing == is comparing the value of the pointer, not the string its pointing to. So the pointer returned will never equal the pointer pointing to "xxx". You need to compare the characters in the strings using strcmp or some variation of it.


if (!strncmp("xxxNameYYY", "xxx", 3))

this should work, the reason that that is failing is because in C string constants are allocated in the .data section because their size is known at compile time. What you end up comparing is address of substring("xxxNameYYY", 0, 3) with the address of "xxx" which are never going to be equal.


That's because your substring function returns a C string (which is a pointer to char values) and you compare that to another C string - so you're effectively comparing two pointer addresses. These two pointers will never be the same, hence you get into the else branch.

The best fix for this is to not use the substring function in the first place; the function allocates memory internally, and it's your responsibility to release the memory (using free). This is quite error-prone.

Instead, you can use the strncmp function to do the comparison. I would wrap that in a startsWith function, like this:

/* Yields true if s starts with t */
bool startsWith( const char *s, const char *t )
{
  return strncmp( s, t, strlen( t ) ) == 0;
}

You could then simplify your code to

if (startsWith("xxxNameYYY", "xxx")) {
     //do this
} else {
     //do that
}


Use strncmp function instead:

if (strncmp("xxxNameYYY", "xxx", 3)==0){
     //do this
} else {
     //do that
}

I your code you compare 2 pointers, not the strings they point to

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜