我有下一个代码,首先我从一个名为hc12的文件中创建一个列表,然后我搜索必须在列表中找到的codop =“BLE”,但我不断收到消息COULDNT FIND CODOP。我不知道为什么,链表运作良好。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct nodo
{
char *code;
struct nodo *next;
}COD;
COD *createNodo(char *instruction);
void insertEnd(char *instruction,COD *last);
COD *lastElement(COD *head);
void remove(char *c);
void searchEndofLine(FILE *fd);
void ignoreSpaces(FILE *fd);
void CodopsList(COD *head);
char *OperandsTable(FILE *hc12);
COD *searchCodop(COD *head,char *codop);
int main()
{
COD *head = NULL,*found;
char *codop = "BLE";
CodopsList(head);
if((found = searchCodop(head,codop)) == NULL)
printf("COULDNT FIND CODOP");
else
printf("CODOP FOUND");
return 0;
}
void searchEndofLine(FILE *fd)
{
int car;
while((car = fgetc(fd))!= '\n')
;
}
void ignoreSpaces(FILE *fd)
{
int car;
do
{
car = fgetc(fd);
}while(car == '\t' || car == ' ');
}
void remove(char *c)
{
char *ptr;
if(((ptr=strchr(c,'\n'))!=NULL)||((ptr=strchr(c,'\t'))!=NULL)||((ptr=strchr(c,' '))!=NULL))
*ptr = '\0';
}
void CodopsList(COD *head)
{
int car;
FILE *hc12;
char *instruction;
COD *last;
if((hc12 = fopen("TABOP.txt","r"))!= NULL)
{
while((car = fgetc(hc12))!= EOF)
{
if(car != '\t')
{
instruction = OperandsTable(hc12);
if(head == NULL)
head = createNodo(instruction);
else
{
last = lastElement(head);
insertEnd(instruction,last);
}
}
else
searchEndofLine(hc12);
}
}
else
printf("Error\n");
}
char *OperandsTable(FILE *hc12)
{
int car,lon = 0,pos;
char *c;
fseek(hc12,-1,SEEK_CUR);
pos = ftell(hc12);
do
{
car = fgetc(hc12);
lon++;
}while(car != '\t');
fseek(hc12,pos,SEEK_SET);
c = (char*)calloc((lon+1),sizeof(char));
fgets(c,lon+1,hc12);
remove(c);
searchEndofLine(hc12);
return c;
}
void insertEnd(char *instruction,COD *last)
{
last->next = createNodo(instruction);
last->next->next = NULL;
last = last->next;
}
COD *lastElement(COD *head)
{
COD *ptr;
ptr = head;
while(ptr->next != NULL)
ptr = ptr->next;
return ptr;
}
COD *createNodo(char *instruction)
{
COD *x;
int t;
t = strlen(instruction);
x = (COD*)malloc(sizeof(COD));
x->codigo = (char*)malloc((t+1)*sizeof(char));
strcpy(x->code,instruction);
x->next = NULL;
return x;
}
COD *searchCodop(COD *head,char *codop)
{
COD *ptr;
for(ptr = head;ptr != NULL;ptr = ptr->next)
{
if(ptr->code == codop)
return ptr;
}
return NULL;
}
答案 0 :(得分:0)
您应该使用strcmp
而不是比较两个数组指针。
在searchCodop
而不是
if(ptr->code == codop)
DO
if (!strcmp(ptr->code, codop))
答案 1 :(得分:0)
您正在调用指针作为值传递,而是使用按引用调用。为此,使用指针指针。像那样:
主要变化
CodopsList(head);
与
CodopsList(&head);
和
更改功能
void CodopsList(COD *head)
与
void CodopsList(COD **head)
在函数CodopsList中使用head作为* head