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
  }

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

compiling with '-ansi' or '--std=c98' works with scanf("%as").
Some background on the m flag, since the GCC/glibc docs don't mention it: gcc.gnu.org/ml/gcc-patches/2007-09/msg01342.html
To use the a modifier, pass -D_GNU_SOURCE to gcc, but of course better use m.
Confusingly, with _GNU_SOURCE defined (in the .c before any #includes), 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. :/
1

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

Comments

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")

Comments

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?

4 Comments

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.
I know what %c does - I just missed that bit. What happens when you use %s instead of %a?
%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()
@nvl - That I did not know. Thanks for the info :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.