Can somebody explain the meaning and the working of this statement of C
scanf( "%*[\n]%[^\n]",arr);
?
Can somebody explain the meaning and the working of this statement of C
scanf( "%*[\n]%[^\n]",arr);
?
Let us break it down:
scanf( "%*[\n]%[^\n]",arr);
%*[\n]
directs scanf to read any characters that are '\n'
. The *
indicated to not save anything. If it does not read at least 1 character, scanf()
returns EOF. Continue until EOF
or until the next character is not a '\n'
.
%[^\n]
directs scanf to read any characters that are not '\n'
. These values are saved in the memory indicated by arr
. This continues until the next character is '\n'
or EOF occurs. If no characters are read, 0 (or EOF) is returned. If at least one was read, and no error, when done, a \0
is appended and scanf()
returns 1.
OP's code is not good code as there is no input limitation. The following would be better. Using fgets()
is even better yet.
char arr[10];
scanf( "%*[\n]%9[^\n]",arr);
In C, scanf
is often used to fill char
arrays. That is, arr
is an array, declared like this:
char arr[99];
When supplied as an argument to a function, it's converted to a pointer to first element. That is, scanf
receives a pointer to the first element of the array, just like it expects with a %[
format specifier.
BTW this is an example of a possible buffer overflow. This example reads one line of text. If the line is long (greater than 98 bytes in my example), scanf
will cause a buffer overrun. Your example actually does something very similar to gets
, which is deprecated because of the overruns that it can cause (and which cannot be prevented). Use a bound for your formats, as described e.g. here.