Search code examples
cstringpointersscanfchar-pointer

How to read a sentence of char pointer with scanf()?


I have a char pointer: char *sentences; and I read it like this:

#include <stdio.h>

int main() {
    char *sentences;
    sentences="We test coders. Give us a try?";
    printf("%s", sentences);
    return 0;
}

but I want to read with scanf() function in c.

scanf("%[^\n]s",S); or scanf("%s",S); didn't work.

How can I do that?


Solution

  • Are you declaring the variable char *sentences; and immediately trying to write to it with scanf? That's not going to work.

    Unless a char * pointer is pointing to an existing string, or to memory allocated with malloc-family functions, assigning to it with scanf or similar is undefined behavior:

    char *sentences;
    scanf("%s", sentences); // sentences is a dangling pointer - UB
    

    Since you haven't actually shared your code that uses scanf and doesn't work, I can only assume that's the problem.

    If you want to assign a user-supplied value to a string, what you can do is declare it as an array of fixed length and then read it with a suitable input function. scanf will work if used correctly, but fgets is simpler:

    char sentence[200];
    fgets(sentence, 200, stdin);
    // (User inputs "We test coders. Give us a try")
    
    printf("%s", sentence);
    // Output: We test coders. Give us a try.
    

    Also, never, ever use gets.