【问题标题】:C - checking for string equalityC - 检查字符串是否相等
【发布时间】:2015-11-29 17:03:54
【问题描述】:

运行程序后我不断收到错误消息。 错误是“分段错误(核心转储)”,我收到了一条注释。

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 语句。比较字符串的那个

【问题讨论】:

  • 要么你得到一个编译器错误(strcmp 注释是关于)要么你得到一个崩溃(分段错误)。您不能真正从同一个程序中获得两者,因为该程序需要在没有错误的情况下构建,您才能运行它并导致崩溃。
  • 据我所知,您尝试将(char**) {"quit"} 隐式转换为char* input。尝试删除那些花括号,它应该是char*?
  • @JoachimPileborg 我怀疑这只是一个编译器警告(如果这是我怀疑的错误,gcc 应该抛出,请参阅上面的评论)
  • cmdline 未定义。没有main() 功能。请提供您实际编译的代码,而不是它的子集。
  • 尝试将char* input = { "quit" }; 替换为char input[] = "quit";。 `.

标签: c string arguments


【解决方案1】:

问题的根源在于两方面:

1) 这个初始化不太理想:

char* input = {"quit"};

建议:

char* input = "quit";

2) fgets() 函数输入尾随<newline><newline> 需要修剪

输入'quit'的实际结果是:

"quit\n"

建议,在调用 fgets() 之后插入:

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

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

【讨论】:

  • 你是对的,代码中缺少很多检查。 +1 为 fgets() 获得 '\n' 以及...
【解决方案2】:

我认为问题在于 input 应该定义为 char* input[] = { "quit" }; 并且条件应该是 strcmp(command, input[0]) == 0

或者 input 应该定义为 char* input = "quit"; 并且条件可以保持在您的示例中。

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

虽然它确实是一个错误,但我无法解释 Segmentation fault 错误。这意味着代码尝试读取(或写入)错误地址(不在您的用户地址空间中的代码)。但在你的情况下,输入只是一个指向堆栈上的指针的指针(它指向初始化数据段中的一个 char 数组,其中包含五个字节:'q'、'u'、'i'、't'、' \0')。所以我得好好想想……

【讨论】:

  • 这一行:strcmp(command, input[0]) == 0 不正确,因为第二个参数也必须是char *,第二个参数只是一个字符,而不是指向以 NUL 结尾的字符数组的指针.
  • @user3629249 char* input[]char**,所以 input[0]char*
  • 在OP贴出的代码中,变量输入定义为char* input = { "quit" };,所以不是char **input[]
  • @user3629249 ...我的答案的第一行是什么? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2015-10-30
  • 1970-01-01
  • 2020-11-09
  • 2014-07-29
  • 2012-06-19
相关资源
最近更新 更多