Reputation: 41
As I said i have problems with linked list.
#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;
I have function with search for word in a linked list and then i want to get all variables as tmpname,tmpstatistic and tmpprice in main and use them for other things.
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;
}
}
When i print them in function it works but when i want to print tmp ones in main they are wrong. If you could help me what to do to get good tmp variables in main. Im not really good at coding :/
Upvotes: 2
Views: 2252
Reputation: 210909
You have to pass pointers to your function search
to get values out. So you can set the result where the pointer refers to.
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
}
}
If you need a copy of "name" use strcpy( *tmpname, first->name );
Call it like this:
search(first,word[MAX],&tmpname, &tmpstatistic, &tmpprice);
An other solution is to return a pointer to thefound element in list, or NULL
if you didn`t find it:
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
}
Upvotes: 2
Reputation: 132994
Well, your function takes the tmpname, tmpstatistic and tmpprice parameters by value. It means that essentially what you pass in main is copied and the copies are assigned meaningful values in your function but the variables you passed in main remain unchanged. Pass those parameters by pointer!
void search(shop *first, char word[MAX], char** tmpname, int* tmpstatistic, int* tmpprice)
And then use, for example,
*tmpstatistic=first->statistic;
Upvotes: 3