Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are scanf arguments allowed to alias? [duplicate]

Tags:

c

scanf

I'm using scanf to extract very regular tabular data. I need to go over it in two passes and can safely ignore some of the arguments some of the time. I want to allocate space for only the strings I care about and a single "discard" string for the others. If I pass this argument multiple times as output, is the behavior defined?

A silly minimal example:

char label[MAX_SIZE], discard[MAX_SIZE];
sscanf(input, "%s %s %s %s", discard, label, discard, discard);
like image 599
porglezomp Avatar asked Jan 06 '17 03:01

porglezomp


People also ask

How many arguments are there in scanf?

Back to the example: scanf takes at least two arguments. The first one is a string that can consist of format specifiers.

How does scanf work in C?

The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list . Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string .

Does scanf block?

scanf() blocks until data is available on the stdin file descriptor. This means that the thread executing this function is not able to perform any other work until scanf() returns.


1 Answers

I cannot find any language in the C11 standard that makes your intended usage invalid.

There seems to be a better solution, though. If you place a * (“assignment suppression character”) after the % in the format string, then the scanf function will parse but not store the input item. Hence, you don't have to (must not, actually) provide a destination argument for it. Seems to be exactly what you need here.

like image 184
5gon12eder Avatar answered Oct 06 '22 10:10

5gon12eder