Hi there, this is my first post here so please tell, if im doing something wrong. Ok so heres the the struct
typedef struct _CMD
{
char nome[100];
char arg[100];
struct _CMD *prox;
}*CMD;
typedef struct _sCMD
{
int cont;
CMD inicio;
CMD fim;
}*sCMD;
The function i use to fill this list:
void add(sCMD com,char str[100],char param[100])
{
CMD novo = (CMD)malloc(sizeof(struct _CMD));
strcpy(novo->nome,str);
strcpy(novo->arg,param);
novo->prox = NULL;
com->cont++;
if(com->inicio == NULL)
{
com->inicio = novo;
com->inicio->prox = com->fim;
}
if(com->fim != NULL)
{
com->fim->prox = novo;
com->fim = novo;
}
if((com->inicio != NULL) && (com->fim == NULL))
{
com->fim = novo;
}
free(novo);
}
After reading into the list, i tried writing everything i had there to see if it worked, and it did. Now the problem is, imagine i had to find the X element of that list, i wrote this function for the deed:
char *find(sCMD com,int i)
{
int j=0;
static char str[100];
CMD aux = (CMD)malloc(sizeof(struct _CMD));
aux = com->inicio;
while (j<i)
{
aux=aux->prox;
j++;
}
strcpy(str,aux->nome);
free(aux);
return str;
}
To test it i run this inside a while, to try displaying all the strings "nome" of each element of the list.
i=0;
while(i < com->cont)
{
printf("%d",i);
puts(find(com,i));
i++;
}
This works for i =0 but after, i get a segmentation fault when calling the function find. further tests showed me it was when i tried aux=aux->prox, now i have no idea why, but the second time this function is called, the list it receives as a parameter is "corrupted", full of trash. Now i hope this isnt too incoherent. Thanks in advance for any attempt of helping me.