【问题标题】:Comparison between pointer and integer warning指针和整数警告的比较
【发布时间】:2012-10-23 15:36:30
【问题描述】:

当我尝试比较指针数组(最初为 NULL)和 char 指针时:

int main(int argc, char **argv){   

    char **list = (char**)malloc(20*sizeof(char)+1);
    char *input = "La li lu le lo";


    if(*list[0] != input[0]) { //or if(list[0][0]!=input[0])
        printf("false: %s", strdict[0]);
    }
}

我经常收到警告:

指针与整数的比较

必须采取什么措施才能消除此警告? 如果我将其修改为:

if(*list[0] != input[0])

警告已删除,但程序崩溃。 提前感谢您的帮助。

【问题讨论】:

  • 定义“运行失败”。它不编译?它崩溃了吗?它说“假:...”?
  • 好吧,1) 删除 malloc cast 并关闭 (。 2) 您正在比较char* list[0] 和char input[0]。在 C 中无效;你需要做list[0][0] != input[0] 3) list 未初始化
  • 它当然不能编译。失踪 ”;”和一个不应该在那里的大括号:P
  • 添加一些关于您希望通过该程序完成什么的信息可能会有所帮助。例如,您是否想查看列表中的第一个字符串是否等于另一个字符串?代码存在一些逻辑问题,难以确定意图是什么。
  • 不确定谁批准了该编辑,但请不要更正/更改 OPs 代码,这就是答案的用途。

标签: c


【解决方案1】:

input[0] 的类型是 char,而 list[0] 的类型是 char*。如果您想比较字符串,请使用strcmp()

然而malloc() 不正确,list 内容未初始化。我认为,根据其名称和类型,list 旨在成为char* 的列表:

/* No need to cast return value of malloc(). */
char **list = malloc(20 * sizeof(char*));

那么每个元素都是char*,需要设置一些char*,也可能是malloc()d:

list[0] = malloc(20); 
/* Populate list[0] with some characters. */

/* Compare to input. */
if (0 == strcmp(list[0], input))
{
    /* Strings equal. */
}

【讨论】:

  • 如果我能再投一个赞成票,因为提到 malloc() 不需要演员
【解决方案2】:

您似乎正在将整数与数组进行比较,因为 List 前面有两颗星。 Input[0] 是一个字符,而 List[0] 是一个数组,如果您查看 List[0][0],那么您将比较两个等效对象。

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2017-06-25
    • 1970-01-01
    相关资源
    最近更新 更多