YoarkYANG
YoarkYANG

Reputation: 303

Scaning a string input keeps failing

I am trying to get an input string by using scanf() in a function, but it keeps failing and I don't know why.

Here is part of my code.

typedef struct node {           
    int id;
    char * name;
    char * address;
    char * group;      
    struct node * next;
} data;

void showG(data * head) {   
    char * n = "";
    int i = 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);
            i = 1;
        }

        current = current->next;
    }
    if (0 == i) {
        printf("no group found");
    }
}

Upvotes: 2

Views: 68

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

In your code,

char * n = "";

makes n point to a string literal which is usually placed in read-only memory area, so cannot be modified. Hence, n cannot be used to scan another input. What you want, is either of below

  • a char array, like

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

     char * n = malloc(128);
    

    Please note, if you use malloc(), after the usage of n is over, you need to free() the memory, too , to avoid memory leak.

Note: after fixing the above issue,change

scanf("%s", n);

to

scanf("%127s", n);

if the allocation is for 128 bytes, to avoid the memory overrun.

Upvotes: 5

Related Questions