-2

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?

Vega
  • 27,856
  • 27
  • 95
  • 103
Sillyon
  • 45
  • 1
  • 2
  • 11
  • The `gets` function is dangerous, and should never be used. Modern C standards no longer support it. See: https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – Govind Parmar Feb 11 '19 at 02:01

1 Answers1

1

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.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85