扫描字符串输入会导致失败

Yoa*_*ANG 2 c scanf

我试图通过scanf()在函数中使用输入字符串,但它一直失败,我不知道为什么.

这是我的代码的一部分.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

在你的代码中,

char * n = "";
Run Code Online (Sandbox Code Playgroud)

使得n指向一个文字串,其通常放置在只读存储区域,所以不能被修改.因此,n不能用于扫描另一个输入.你想要的是下面的任何一个

注意:修好上述问题后,请更改

scanf("%s", n);
Run Code Online (Sandbox Code Playgroud)

scanf("%127s", n);
Run Code Online (Sandbox Code Playgroud)

如果分配是针对128字节的,则避免内存溢出.