char 指针和 IF 语句
我有一个从函数返回的 char 指针,我想使用 IF 语句仔细检查它的值,我应该如何在 C 中实现这个值。
substring 函数来自 here
我想要这样的东西,
if (substring("xxxNameYYY",0,3)=="xxx"){
//do this
} else {
//do that
}
上面的 if 语句总是转到“do that”部分。
谢谢
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能像C中那样比较字符串,你必须使用
strcmp(str1, str2) == 0
来检查它们是否相等。在你的情况下:
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:
由于这是一个指针,因此执行 == 是比较指针的值,而不是其指向的字符串。所以返回的指针永远不会等于指向“xxx”的指针。您需要使用 strcmp 或其某些变体来比较字符串中的字符。
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.
这应该可以工作,失败的原因是因为在 C 中字符串常量是在 .data 部分中分配的,因为它们的大小在编译时是已知的。您最终比较的是
substring("xxxNameYYY", 0, 3)
的地址与“xxx”的地址,它们永远不会相等。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.这是因为您的
substring
函数返回一个 C 字符串(它是指向char
值的指针),并且您将其与另一个 C 字符串进行比较 - 因此您实际上是在比较两个指针地址。这两个指针永远不会相同,因此您进入 else 分支。对此的最佳解决方法是首先不要使用
substring
函数;该函数在内部分配内存,您有责任释放内存(使用free
)。这是非常容易出错的。相反,您可以使用
strncmp
函数来进行比较。我会将其包装在startsWith
函数中,如下所示:然后您可以将代码简化为
That's because your
substring
function returns a C string (which is a pointer tochar
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 (usingfree
). This is quite error-prone.Instead, you can use the
strncmp
function to do the comparison. I would wrap that in astartsWith
function, like this:You could then simplify your code to
使用 strncmp 函数代替:
我的代码比较 2 个指针,而不是字符串他们指出
Use strncmp function instead:
I your code you compare 2 pointers, not the strings they point to