gpt4 book ai didi

无法在链表上找到元素

转载 作者:行者123 更新时间:2023-11-30 17:41:41 25 4
gpt4 key购买 nike

我有下一个代码,首先我从名为 hc12 的文件创建一个列表,然后我搜索必须在列表中找到的 codop =“BLE”,但我不断收到消息“无法找到 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;
}

最佳答案

您应该使用strcmp而不是比较两个数组指针。

searchCodop 中而不是

if(ptr->code == codop)

if (!strcmp(ptr->code, codop))

关于无法在链表上找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com