[英]strcmp() not working for char *array and char const comparison
I am facing problem with following code. 我遇到以下代码的问题。 I want to compare the input words. 我想比较输入的单词。 The strcmp is not returning 0 for same char strings. 对于相同的字符字符串,strcmp不会返回0。 It is pretty straightforward problem but I am not able to figure out where I am going wrong. 这是一个非常简单的问题,但是我无法弄清楚哪里出了问题。
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char message[255];
fgets(message,254,stdin);
char *command[2];
char *p;
int i=0;
for(p=strtok(message," ");p!=NULL;p=strtok(NULL," "))
{
command[i]=p;
fprintf(stderr,"%s\n",command[i]);
}
int dif=strcmp(command[0],"get");
fprintf(stderr,"dif is:%d\n",dif);
}
You never increment i
in your for
loop. 您永远不会在for
循环中增加i
。 Thus, a pointer to every word in your message is written to command[0]
. 因此,将指向消息中每个单词的指针写入command[0]
。
Try this: 尝试这个:
for(p=strtok(message," ");p!=NULL;p=strtok(NULL," "))
{
command[i]=p;
fprintf(stderr, "command[%d]==%s\n", i, command[i]);
i += 1;
}
But note that the fixed (and relatively small) size of your command
array is a bug waiting to happen. 但是请注意, command
数组的固定大小(相对较小)是一个等待发生的错误。 Consider what happens to your 2-length array if the user enters 3 or more words. 考虑如果用户输入3个或更多单词,则2长度数组会发生什么情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.