strcmp 给出分段错误

Sac*_*iya 6 c pointers

这是我给出分段错误的代码

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    char *get;
    scanf("%s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助;

aja*_*jay 4

char *get;
Run Code Online (Sandbox Code Playgroud)

上面的语句定义了get一个指向字符的指针。它可以存储 类型的对象的地址char,而不是字符本身。问题出在scanfstrcmp调用上。您需要定义一个字符数组来存储输入字符串。

#include <stdio.h>
#include <string.h>

int main(void) {
    // assuming max string length 40
    // +1 for the terminating null byte added by scanf

    char get[40+1];

    // "%40s" means write at most 40 characters
    // into the buffer get and then add the null byte
    // at the end. This is to guard against buffer overrun by
    // scanf in case the input string is too large for get to store

    scanf("%40s", get);
    int k = strcmp("sachin", get);
    printf("%d", k);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)