检查字符串数组是否为空

发布于 2025-01-04 17:42:58 字数 418 浏览 0 评论 0原文

我声明了以下字符串数组: char *arrayIndi​​ces[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")

第二个结果是错误的。 arrayIndi​​ces[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吖咩 2025-01-11 17:42:58

您需要在此处使用撇号,而不是引号:

if (arrayIndi​​ces[i] == '\0')

You need to use apostrophes, not quotes, here:

if (arrayIndices[i] == '\0')

ぃ弥猫深巷。 2025-01-11 17:42:58

strcmp 失败,因为没有内存分配给 arrayIndi​​ces[i]。您可以像这样检查是否为空

if (!arrayIndices[i] || !arrayIndices[i][0])
   /* Empty. */

The strcmp fails because there's no memory allocated to arrayIndices[i]. You can check for empty like so:

if (!arrayIndices[i] || !arrayIndices[i][0])
   /* Empty. */
望笑 2025-01-11 17:42:58

@cnicutar 的答案是正确的,但对我来说看起来有点太简洁了。我想写:

if ( NULL == arrayIndices[i] || 0 == strlen(arrayIndices[i]) )
    /* empty */

您担心 strlen 是否会占用太多 CPU 时间?不用担心,

另一方面,@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

if ( NULL == arrayIndices[i] || 0 == strlen(arrayIndices[i]) )
    /* empty */

You're worrying if strlen might take too much CPU time? Never worry about it,

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 :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文