tags:

views:

698

answers:

4

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

  char *string;
  if (scanf ("%as",&string) != 1){
    //some code
  }
  else{
   printf("%s\n", *string);
   free(string);
   //some code
  }

Edit:
scanf("%ms") also works.(see answers)

A: 

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?

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

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

Tronic
A: 

'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
+2  A: 

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.

Cirno de Bergerac
compiling with '-ansi' or '--std=c98' works with scanf("%as").
N 1.1