【问题标题】:Checking pointer of *char[] is NULL without upsetting gcc在不破坏 gcc 的情况下检查 *char[] 的指针为 NULL
【发布时间】:2013-01-04 02:49:21
【问题描述】:

我有 char *words[] 保存不同长度的字符串。

words 包含 5 个动态分配的字符串:["zero","one","two","three","four"]

我释放其中一个字符串并将其指针设置为NULL,如下所示:

free(words[1]);
*(words[1]) = NULL;

稍后我循环遍历words 数组并检查每个项目是否为NULL,如下所示:

if(*words[i] == NULL)

当我编译 gcc 时说warning: comparison between pointer and integer。一些谷歌搜索表明我可以通过将检查更改为:

if(*words[i] == 0)if(*words[i])

我知道它很挑剔,但这些检查并不像使用 NULL 时那样清晰。有没有办法在不更改 gcc 标志或使用 #define-esque 解决方案的情况下使用 NULL 进行比较?


作为参考,我的编译命令是:

gcc -m32 -g -O0 -std=gnu99 -Wall -Wfloat-equal -Wtype-limits -Wpointer-arith -Wlogical-op -fno-diagnostics-show-option  -m32  words.c   -o words

【问题讨论】:

    标签: c pointers gcc syntax null


    【解决方案1】:

    代码没有按照您的想法执行。 *words[i] 为您提供第 i 个字符串中的第一个字符(即 char),而不是第 i 个字符串本身(即 char*)。你想要的只是words[i]。请记住,在 C 中 char* words[] 基本上是 char** words

    警告来自 C 认为 char 是一个整数这一事实。在这种情况下,编译器警告你是一件好事!

    【讨论】:

    • 谢谢!我会很快测试一下,假设你是对的,我会批准你的答案
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多