扫描字符串输入一直失败

Scaning a string input keeps failing

我试图通过在函数中使用 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");
    }
}

在您的代码中,

char * n = "";

使n指向一个字符串字面量,通常放在只读内存区,所以不能修改的。因此,n 不能用于 扫描 另一个输入。你想要的是以下任何一种

  • 一个char数组,如

    char n[128] = {0};
    
  • 指向 char 的指针,具有适当的内存分配。

     char * n = malloc(128);
    

    请注意,如果您也使用 malloc(), after the usage of n is over, you need to free() 内存,以避免内存泄漏。

注意:解决上述问题后,更改

scanf("%s", n);

scanf("%127s", n);

如果分配的是 128 字节,以避免内存溢出。