9

I am trying to read input using scanf and storing into char * dynamically as specified by GCC manual, But it is giving a compile time error.

  char *string;
  if (scanf ("%as",&string) != 1){
    //some code
  }
  else{
   printf("%s\n", *string);
   free(string);
   //some code
  }
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
N 1.1
  • 12,418
  • 6
  • 43
  • 61

4 Answers4

10

The a modifier to scanf won't work if you are compiling with the -std=c99 flag; make sure you aren't using that.

If you have at least version 2.7 of glibc, you can and should use the m modifier in place of a.

Also, it is your responsibility to free the buffer.

Nietzche-jou
  • 14,415
  • 4
  • 34
  • 45
  • compiling with '-ansi' or '--std=c98' works with scanf("%as"). – N 1.1 Feb 24 '10 at 22:31
  • 2
    Some background on the `m` flag, since the GCC/glibc docs don't mention it: http://gcc.gnu.org/ml/gcc-patches/2007-09/msg01342.html – Michael Burr Jul 09 '12 at 19:09
  • 1
    To use the `a` modifier, pass -D_GNU_SOURCE to gcc, but of course better use `m`. –  Nov 11 '12 at 14:45
  • Confusingly, with _GNU_SOURCE defined (in the .c before any `#include`s), gcc 4.9.2 with `-std=gnu99` warns that `%a` wants a `float*`, but you're passing it a `char **`. But the behaviour matches `%m[`. It took me a while to remember that `%a` was a dynamic allocation conversion, because the man page doesn't mention the old GNU meaning anywhere near the other modifiers. Even the new POSIX.1-2008 `%ms` / `%m[` only gets mentioned in a dense paragraph in with the field width stuff. Really easy to miss. :/ – Peter Cordes Sep 11 '15 at 05:37
1

Do you have GNU extensions enabled? Standard C doesn't have a modifier at all.

Tronic
  • 10,250
  • 2
  • 41
  • 53
1

'Dynamic String Input' with scanf("%as") will work if the -ansi or -std=c89 flag is enabled.
Compile using gcc -ansi

Or else you can use scanf("%ms")

N 1.1
  • 12,418
  • 6
  • 43
  • 61
0

I've had limited experience with GCC, but I've never seen a %a modifier for scanf. Have you tried replacing the %a with %s in the third line you provided?

  • Please refer to the link provided. FYI %c stores only 1 char. I am trying to dynamically allocate memory for storing a complete string of 0-9a-zA-z characters. – N 1.1 Feb 24 '10 at 22:07
  • I know what `%c` does - I just missed that bit. What happens when you use `%s` instead of `%a`? –  Feb 24 '10 at 22:12
  • 2
    %s will work if you already have allocated memory. whereas %as (with a flag) allocates required memory itself to *variable which can later be freed() – N 1.1 Feb 24 '10 at 22:20
  • @nvl - That I did not know. Thanks for the info :) –  Feb 25 '10 at 01:34