C 问题陈述:搜索一个整数数组,找到第一个负整数,如果存在,返回它在数组中的位置。 我知道我可以通过使用索引来做到这一点,但是,我只是想知道为什么程序没有进入 if 条件?即使我进行转换,代码也永远不会进入 if 条件。
void find_negative(int argc, char *argv[])
{
int i = 0;
//ignore the first string of arguments because it will be "./problem1.3.c"
for(i =1; i<argc;i++)
{
if(*(argv+i)==2) <-------------------------this is where I get stuck (problem)
{
printf("found it at %d location.\n", i);
}
else
{
printf("All positive.\n");
}
}
}
int main(int argc , char *argv[])
{
find_negative(argc, argv);
return 0;
}
最佳答案
(argv+i)
的类型是char**
。
*(argv+i)
的类型是char*
。
在一行中,
if(*(argv+i)==2)
您正在尝试将 char*
与类型为 int
的 2 进行比较。这解释了编译器错误消息。
也许您想从参数中提取一个整数并将其与 2 进行比较。那么,您需要使用:
if(atoi(*(argv+i))==2)
关于c - 指针与整数的误差比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090236/