【发布时间】:2013-10-17 06:04:15
【问题描述】:
char* mystr = calloc(25, sizeof(char));
fgets(mystr, 25, stdin); // I enter "6 7 *" in here, without the quotes
char* tok;
tok = strtok(mystr, " ");
while (tok != NULL) {
if(strcmp(tok, "*") == 0)
//It never meets this condition, but I don't understand why
else
//do something else here
tok = strtok(NULL, " ");
}
问题是strcmp(tok, "*") 永远不会返回相等,即使tok 从原始字符串中读取星号。我不明白为什么它从来不满足这个条件。
【问题讨论】:
-
sizeof(char)是1。 -
了解如何使用调试器(如
gdb)。也许试试strncmp(tok, "*", 1) -
在调试器中逐行检查代码,看看
strtok返回什么。 -
不仅是
sizeof(char)1,最好不要不必要地重复char:TYPE *ptr = calloc(N, sizeof *ptr)。