第一个 if 条件导致段错误。我无法真正理解为什么,因为我在其他地方使用类似的 if 子句和关系运算符。感谢您提前提供的帮助。
int foo(char *str1,char **str2, char **str3)
{
char *token1;
char *token2;
char *token = strtok(str1, "\"");
int spaces = strcmp(token," ");
int parenthesis = strcmp("{",token);
if((token == NULL) || ((spaces != 0) && (parenthesis != 0)))
{
printf("ERR.\n");
return 0;
}
token = strtok(NULL, "\"");
if(token == NULL)
{
printf("2ERR\n");
return 0;
}
token1= strtok(NULL, "\"");
if(token1 == NULL || strcmp(token1," -> ") != 0)
{
printf("3ERR\n");
return 0;
}
token2 = strtok(NULL, "\"");
return 1;
}
最佳答案
如果不使用char[]
,strtok
将会崩溃。您可以使用 strcpy
来绕过它。
char str[80];
strcpy(str, str1);
char *token = strtok(str, "\"");
我不确定您要做什么,但您的代码将在小更改后运行而不会崩溃。
#include <stdio.h>
#include <string.h>
int foo(char *str1,char **str2, char **str3)
{
char *token1;
char *token2;
char str[80];
strcpy(str, str1);
char *token = strtok(str, "\"");
int spaces = strcmp(token," ");
int parenthesis = strcmp("{",token);
if((token == NULL) || ((spaces != 0) && (parenthesis != 0)))
{
printf("ERR.\n");
return 0;
}
token = strtok(NULL, "\"");
if(token == NULL)
{
printf("2ERR\n");
return 0;
}
token1= strtok(NULL, "\"");
if(token1 == NULL || strcmp(token1," -> ") != 0)
{
printf("3ERR\n");
return 0;
}
token2 = strtok(NULL, "\"");
return 1;
}
int main() {
char * c1, * c2, * c3;
c1 = "foobaz";
c2 = "bar";
c3 = "baz";
int i = foo(c1, &c2, &c3);
return 0;
}
关于c - if 条件下使用关系运算符的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361042/