C-检查字符串是否相等

C-检查字符串是否相等,c,string,arguments,C,String,Arguments,运行程序后,我一直收到一个错误。 错误是“分段错误(堆芯转储)”,我得到一个注释 note: expected ‘const char *’ but argument is of type ‘char’ extern int strcmp (const char *__s1, const char *__s2) 这是我的代码: int main() { char cmdline[100]; printf ("esp> "); fgets( cmdline, sizeof(

运行程序后,我一直收到一个错误。 错误是“分段错误(堆芯转储)”,我得到一个注释

note: expected ‘const char *’ but argument is of type ‘char’
 extern int strcmp (const char *__s1, const char *__s2)
这是我的代码:

int main()
{
  char cmdline[100];
  printf ("esp> ");
  fgets( cmdline, sizeof( cmdline ), stdin );

  char *args[4] = { NULL };
  char *pchcaus;

  pchcaus = strtok (cmdline," ");

  int i = 0;
  while (pchcaus != NULL)
  {
    args[i++] = pchcaus;
    pchcaus = strtok (NULL, " ");
  }

  char* command = args[0];
  char* argumentOne = args[1];
  char* argumentTwo = args[2];
  char* input = { "quit" };

  printf ("%s", command);    // this prints "quit"

  if (strcmp(command, input) == 0) {  // this is not working. why ?
    printf("Bye.\n" );
  }

  return 0;
}

如果我输入quit,它将返回“分段错误(核心转储)”。除了最后一个if语句外,其他一切都正常。比较字符串的那一个

我假设问题是
input
应该定义为
char*input[]={“quit”}且条件应为strcmp(命令,输入[0])==0

input
应定义为
char*input=“退出”并且条件可以保持如示例中所示

在您的示例中,
input
声明为
char**
,但在
strcmp
中用作
char*
。这是在警告中声明的


但是,尽管这确实是一个bug,但我无法解释
分段错误
错误。这意味着代码试图读取(或写入)错误的地址(不在用户地址空间中的代码)。但在本例中,输入只是指向堆栈上指针的指针(指向初始化数据段中的字符数组,其中包含五个字节:“q”、“u”、“i”、“t”、“0”)。所以我必须仔细考虑一下…

问题的根源有两个方面:

1) 此初始化不太理想:

char* input = {"quit"};
建议:

char* input = "quit";
2)
fgets()
函数输入尾随的
。需要修剪的

输入“退出”的实际结果是:

"quit\n"
建议在调用
fgets()
后插入以下内容:

char *NewLine = NULL;
if( NULL != (NewLine = strstr( cmdline, "\n" ) ) )
{
     *NewLine = '\0';
}

代码还应该检查(!=NULL)来自
fgets()
的返回值,以确保输入操作成功

或者您得到了编译器错误(strcmp
注释是关于此错误的),或者您得到了崩溃(分段错误)。你不可能从同一个程序中同时拥有这两个元素,因为程序需要在没有错误的情况下构建,这样你才能运行它并获得崩溃。据我所知,你试图隐式地将
(char**){“quit”}
转换为
char*input
。试着去掉那些大括号,它应该是一个
char*
?@JoachimPileborg,我怀疑它只是一个编译器警告(如果是我怀疑的错误,应该抛出
gcc
,请参见上面的注释)
cmdline
未定义。没有
main()
函数。请提供实际编译的代码,而不是它的子集。请尝试替换
char*input={“quit”}
字符输入[]=“退出”`。这一行:
strcmp(命令,输入[0])==0
不正确,因为第二个参数也必须是
char*
,第二个参数只是一个字符,而不是指向以NUL结尾的字符数组的指针。@user3629249
char*input[]
char**
,因此
input[0]
char*
。在OP发布的代码中,变量输入定义为
char*input={“quit”},所以它不是
char**input[]
@user3629249…我的答案的第一行是什么?:)你是对的,代码中缺少很多检查+1用于fgets()并获取“\n”。。。