The main problem is naming a new element in the list:
void insChild(LIST* l, char name[]) {
...
NO* new;
...
new = (NO*)malloc(sizeof(NO));
new->child = name; //<---aqui
Being child
a pointer, it will be pointing to the variable passed as parameter:
scanf("%s", name /*<---esta*/);
And each time you insert another node you will be pointing to the same variable name
. What you want to do is actually allocate space for a new string
with malloc
and copy the name to that string
with strcpy
:
void insChild(LIST* l, char name[])
{
...
NO* new;
...
new = (NO*)malloc(sizeof(NO));
new->child = malloc((strlen(name)+1)*sizeof(char));
strcpy(new->child,name);
Note that I used the strlen
to find out the size of the name and allocate a string
with that size. That size had to be increased by 1
to contemplate the terminator \0
of string
. All this will entail adding the reference to string.h
:
#include <string.h>
Documentation for the strcpy
and to the strlen
Other problems
The name problem has been solved, but there are still some things you need to get right and can improve:
- All the functions they receive
LIST
shall now receive LIST*
because this avoids the copy of the whole structure in the call to function
- Should not use
new
as variable name and will bring you problems if you migrate the code to C++, because it will be a reserved word
The Segmentation Fault which you indicated in the comments is due to the finding function of the node to be removed. Not only should the condition be changed but the pointer failed to start bef
. It should be like this:
NO* nChild(LIST *l, int n, NO** bef)
{
NO* p = l->head->next;
//faltou aqui iniciar o ponteiro que ficava inválido não houvessem elementos
*bef = l->head;
int i = 0;
//ajustei aqui para n, e int del = rand() % slist; na função DelChild
while ((p != l->head) && (i < n))
{
*bef = p;
p = p->next;
i++;
}
if (i >= SizeList(l)) return NULL; //troquei a condição para facilitar
else return p;
}
View the code with all these changes working on Ideone
Thanks Isac, gave it right, but now it gave a problem of Segmentation fault. By inserting "Ana", "Bana" and "Joao" and removing the second time of the Gmentation fault. You could tell me why?
– Juny
@Juny has more problems than copying itself. I already point them out as soon as I have a little time now.
– Isac
Beauty @Isac, no rush. I’m on hold. Thank you!
– Juny
@Juny I already edited the question, checking things to improve/fix, and now the removing part is actually working
– Isac