-6

Can somebody explain the meaning and the working of this statement of C

scanf( "%*[\n]%[^\n]",arr);

?

sjsam
  • 19,686
  • 3
  • 43
  • 88
  • 2
    I'm voting to close this question as off-topic because post complete code. – Karoly Horvath Jul 28 '16 at 17:37
  • 4
    A better question would be to tell us what you think it does, why you think that, and if the behavior of the program does not match your expectation, ask for specific help in a much more pointed fashion. – R Sahu Jul 28 '16 at 17:40
  • 1
    You need to look at how `arr` is declared. – FredK Jul 28 '16 at 17:55

2 Answers2

2

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);
Rudy Velthuis
  • 27,475
  • 4
  • 43
  • 84
chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213
2

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.

Community
  • 1
  • 1
anatolyg
  • 23,079
  • 7
  • 51
  • 113