c-在链表中搜索字符串并获取所有变量



正如我所说,我对链表有问题。

#include <stdio.h>
#include <stdlib.h>
#define MAX 30
typedef struct elem{
    char name[MAX];
    int statistic;
    int price;
    struct elem *next;
    struct elem *prev;
}   shop;

我有在链表中搜索单词的功能,然后我想把所有变量都作为tmpname、tmpstatistic和tmpprice,并把它们用于其他事情。

void search(shop *first, char word[MAX], char tmpname[MAX], int tmpstatistic, int tmpprice)
{
    while (first!=NULL && strcmp(first->name, word) != 0)
    {
        first = first->next;
    }
    if (first != NULL && strcmp(first->name, word)==0)
    {
        printf("%s found! n", word);
        printf("%s n", first->name);
        printf("%d n", first->statistic);
        printf("%d n", first->price);
        tmpname=first->name;
        tmpstatistic=first->statistic;
        tmpprice=first->price;
    }
}

当我在函数中打印它们时,它是有效的,但当我想在主函数中打印tmp时,它们是错误的。如果你能帮我做些什么来获得好的tmp变量。我真的不擅长编码:/

好吧,您的函数按值获取tmpname、tmpstatistic和tmpprice参数。这意味着,您在main中传递的基本上是被复制的,并且副本在函数中被分配了有意义的值,但您在main传递的变量保持不变。通过指针传递这些参数!

void search(shop *first, char word[MAX], char** tmpname, int* tmpstatistic, int* tmpprice)

然后使用,例如

*tmpstatistic=first->statistic; 

您必须将指针传递到函数search才能获取值。因此,您可以设置指针指向的结果。

void search(shop *first, char word[MAX], char **tmpname, int* tmpstatistic, int* tmpprice)
                                           // ^             ^                  ^
{
    while (first!=NULL && strcmp(first->name, word) != 0)
    {
        first = first->next;
    }
    if (first != NULL && strcmp(first->name, word)==0)
    {
        printf("%s found! n", word);
        printf("%s n", first->name);
        printf("%d n", first->statistic);
        printf("%d n", first->price);
        *tmpname=first->name;           // assigne pointer to first->name where tmpname refers to
        *tmpstatistic=first->statistic; // assigne first->statistic where tmpstatistic refers to
        *tmpprice=first->price;         // assigne first->pricewhere tmppricerefers to
    }
}

如果您需要"名称"的副本,请使用strcpy( *tmpname, first->name );

这样称呼它:

search(first,word[MAX],&tmpname, &tmpstatistic, &tmpprice); 

另一种解决方案是返回一个指向列表中查找到的元素的指针,如果找不到,则返回NULL

shop* search(shop *first, char word[MAX])
{
    while (first!=NULL && strcmp(first->name, word) != 0)
    {
        first = first->next;
    }
    return first; // If you didn't find word in list, first is NULL, else first is the found elment
}

相关内容

  • 没有找到相关文章

最新更新