Search code examples
cscanfcstring

C read string from std error


I want to read string from standart input and output it in on console. I use this way:

char* cmdline;

do{
    scanf("%s\n", &cmdline);
    printf("%s\n", cmdline);
}while(cmdline != "quit");

But this doesn't work. I have this error Segmentation fault (core dumped)


Solution

  • char* cmdline
    

    is a pointer. You are not allocating space for storing the string. You should do:

    cmdline = malloc(size_of_string);
    

    for allocating dynamic memory for storing the string. Otherwise use an array of char instead of a pointer:

    char cmdline[size_of_string];