Problem with switch C

1

I have a code in C, and without the switch, it works fine, but with switch, when inserting name in the list, it replaces all the name of the list with the same one.

void insChild(LIST* l, char name[]) {
  NO* new;
  NO* p;
  p = LastChild(*l);
  new = (NO*)malloc(sizeof(NO));
  new->child = name;
  new->next = l->head;
  p->next = new;
}
    
asked by anonymous 16.10.2017 / 19:04

1 answer

1

The main problem is in naming a new element in the list:

void insChild(LIST* l, char name[]) {
  ...
  NO* new;
  ...
  new = (NO*)malloc(sizeof(NO));
  new->child = name; //<---aqui

Since% is a pointer, it will point to the variable passed as a parameter:

scanf("%s", name /*<---esta*/);

And every time you insert another node it will be pointing to the same variable child . What you want to do is actually allocate space for a new name with string and copy the name to that malloc with string :

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 strcpy to find out the name size and to allocate a strlen to that size. This size had to be increased in% with% to include the terminator string of 1 . All this will involve adding the reference to string :

#include <string.h>

Documentation for the string.h and for the strcpy

Other issues

The naming problem has been solved, but there are still some things you need to get right and can improve:

  • All functions that receive strlen should now receive LIST because this prevents copying of the entire structure in the function call
  • You should not use LIST* as the variable name, and will cause you problems if you migrate the code to C ++ because it will be a reserved word in it
  • The Segmentation Fault that you indicated in the comments should be the find function of the node to remove. Not only should the condition be changed, but the new pointer has to be started. It should look 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;
    }
    

See the code with all these changes working on Ideone

    
16.10.2017 / 19:43