正如我所说,链接列表存在问题。
#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;
我在链接列表中搜索单词的功能,然后我想在main中将所有变量作为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变量。我不擅长编码:/
答案 0 :(得分:3)
好吧,你的函数采用tmpname,tmpstatistic和tmpprice参数按值。这意味着你在main中传递的主要是复制,并且在函数中为副本分配了有意义的值,但是你在main中传递的变量保持不变。通过指针传递这些参数!
void search(shop *first, char word[MAX], char** tmpname, int* tmpstatistic, int* tmpprice)
然后使用,例如,
*tmpstatistic=first->statistic;
答案 1 :(得分:2)
您必须将指针传递给函数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);
另一个解决方案是返回指向列表中的found元素的指针,如果你找不到它,则返回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
}