[英]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.