检查字符串数组是否为空
我声明了以下字符串数组: char *arrayIndices[100] = {0};
我与 recp->ut_line 进行比较,声明为:
struct utmp {
....
char ut_line[32]
}
using:
strcmp(arrayIndices[i], (char*)recp->ut_line))
这给了我一个分段错误。 我也在 gdb 中尝试过这些:
if (arrayIndices[i] == NULL)
if (arrayIndices[i] == "\0")
第二个结果是错误的。 arrayIndices[i] 打印出来时显示值为 0x0。
I've declared the following array of strings:
char *arrayIndices[100] = {0};
I do a comparison with recp->ut_line which is declared as:
struct utmp {
....
char ut_line[32]
}
using:
strcmp(arrayIndices[i], (char*)recp->ut_line))
This gives me a segmentation error.
I've also tried these in gdb:
if (arrayIndices[i] == NULL)
if (arrayIndices[i] == "\0")
The second one turns up false. arrayIndices[i] shows a value of 0x0 when printed out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在此处使用撇号,而不是引号:
if (arrayIndices[i] == '\0')
You need to use apostrophes, not quotes, here:
if (arrayIndices[i] == '\0')
strcmp
失败,因为没有内存分配给arrayIndices[i]
。您可以像这样检查是否为空:The
strcmp
fails because there's no memory allocated toarrayIndices[i]
. You can check for empty like so:@cnicutar 的答案是正确的,但对我来说看起来有点太简洁了。我想写:
您担心
strlen
是否会占用太多 CPU 时间?不用担心,http://c2.com/cgi/wiki?PrematureOptimization
<块引用>
过早的优化是万恶之源。
另一方面,@StilesCrisis 的答案是错误的。如果我有足够的声誉,我会投反对票!事实上,我很惊讶地发现它甚至可以编译。 (可能是由于大多数平台上的
'\0' == 0 == NULL
)题外话:您可能对 Ruby 提供的
String#blank?
方法感兴趣导轨:-)@cnicutar's answer is correct, but looks a bit too succint for me. I'd like to write
You're worrying if
strlen
might take too much CPU time? Never worry about it,http://c2.com/cgi/wiki?PrematureOptimization
On the other hand @StilesCrisis's answer is WRONG. I would downvote it if I had enough reputation! Actually I'm surprised to realize that it even compiles. (Maybe due to
'\0' == 0 == NULL
on the most platforms)Off topic: you may be interested in
String#blank?
method provided by Ruby on Rails :-)