[英]Seg Fault using strcmp with * char
我有这个结构
typedef struct no
{
char command[MAX_COMMAND_LINE_SIZE];
struct no * prox;
} lista;
lista *listaCommand = NULL;
我正在使用一个似乎工作正常的简单函数来填充listaCommand,因为我可以毫无问题地读取值,但如果我尝试比较,就像
strcmp(listaCommand->prox>command, ">")
我只是得到一个分段错误,即使值>在那里,为什么会发生这种情况?
strcmp(listaCommand->prox>command, ">")
应该
strcmp(listaCommand->prox->command, ">")
在您的代码中, listaCommand->prox>command
将被视为比较操作,使用>
运算符。 C中的比较返回整数,如果为false,则返回0,否则返回非零。 它很有可能返回0
,这不是有效的内存地址。 因此,分段错误。
更改
strcmp(listaCommand->prox>command, ">")
至
strcmp(listaCommand->prox->command, ">")
分配内存!!!
typedef struct no
{
char str[20];
struct no * prox;
} lista;
lista *listaCommand = NULL;
int main(int argc, char** argv)
{
listaCommand = malloc(sizeof(lista));
listaCommand->prox = malloc(sizeof(lista));
strcpy(listaCommand->prox->str, "aaa");
printf("%d\n", strcmp(listaCommand->prox->str, ">>"));
free(listaCommand->prox);
free(listaCommand);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.