-1

I want scanf string and set pointer to him. String input is each time different so I can't set like char input[20]. So far no success.

int main(void) {
    char input;
    char *input_string = input;
    scanf("%s", &input_string);

    int i = 0; 
    while (input_string[i] != '\0') {
        printf('%d', input_string[i]);
        i++;
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Jakub Menšík
  • 174
  • 1
  • 10
  • 8
    I afraid you might need to get a good C book and read through it. This code has more wrong things than the right ones. – Eugene Sh. Mar 08 '19 at 19:52
  • 2
    This shouldn’t compile. You need to allocate memory for the data. It doesn’t need to be the exact amount, it should be the maximum possible. And you should define that maximum also in the `scanf` call. – Sami Kuhmonen Mar 08 '19 at 19:52
  • With pointer, the relevant duplicate is https://stackoverflow.com/questions/18403154/when-should-i-use-ampersand-with-scanf – Antti Haapala -- Слава Україні Mar 08 '19 at 20:33
  • 2
    Save time, enable all compiler warnings. Perhaps receive output like " warning: initialization makes pointer from integer without a cast [-Wint-conversion]", "warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=]", "warning: multi-character character constant [-Wmultichar]", "warning: passing argument 1 of 'printf' makes pointer from integer without a cast [-Wint-conversion]". This feedback is much faster than posting on Stack overflow. – chux - Reinstate Monica Mar 08 '19 at 20:42
  • `char *input_string = input;` is wrong. `input_string` is a pointer, but `input` is a char, you can't assign them. – Barmar Mar 08 '19 at 20:49
  • You can do `char *input_string = &input;`, but you can't use `input_string` as a string. A string is an array of characters ending with a null byte, but `input` is just a single character. – Barmar Mar 08 '19 at 20:50
  • @blackoutnet: you could undelete your answer and make these corrections: define `input_string` as a `char` array and use `if (!fgets(input_string, sizeof input_string, stdin)) return 0;`. A `for` loop would be more concise. print a newline after the loop and return 0. – chqrlie Mar 09 '19 at 09:00

1 Answers1

0

On a POSIX system, you can use the m modifier to automatically allocate memory for the string

char *input_string;
scanf("%ms", &input_string);

Note that in order to avoid leaking memory, you will eventually need to call free(input_string); to free the allocated memory.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226