c - Scaning a string input keeps failing -


i trying input string using scanf() in function, keeps failing , don't know why.

here part of code.

typedef struct node {                int id;     char * name;     char * address;     char * group;           struct node * next; } data;  void showg(data * head) {        char * n = "";     int = 0;     data * current = head;     scanf("%s", n);     printf("the group of %s is\n", n);      while (current != null) {         if (0 == strcmp(current->group, n)) {             printf("%d,%s,%s\n", current->id, current->name, current->address);             = 1;         }          current = current->next;     }     if (0 == i) {         printf("no group found");     } } 

in code,

char * n = ""; 

makes n point string literal placed in read-only memory area, cannot modified. hence, n cannot used scan input. want, either of below

  • a char array, like

    char n[128] = {0}; 
  • a pointer char proper memory allocation.

     char * n = malloc(128); 

    please note, if use malloc(), after usage of n over, need free() memory, , avoid memory leak.

note: after fixing above issue,change

scanf("%s", n); 

to

scanf("%127s", n); 

if allocation 128 bytes, avoid memory overrun.


Comments