What kind of data entry is this? scanf("%m[ ]

Asked

Viewed 67 times

3

I found this in a C program:

int k;
char* nometreino;
char* nometeste;

FILE* arquitreino;
FILE* arquiteste;

scanf("%m[^ ] %m[^ ] %d", &nometreino, &nometeste, &k);

arquitreino = fopen(nometreino, "r");
arquiteste = fopen(nometeste, "r");

In this case he is declaring the variables to open the file, however I got lost in this scanf %m[^ ] and after it, will be opened the file that are in the variables nometreino and nometeste right?

How it works?

1 answer

4


It is not standard and most compilers do not accept this, so it is a good reason not to use.

If using GCC you can apply to the scanf() allocate the memory needed for the data that will be stored in the variable there. Then the first placeholder will create a buffer to store a data and this will be pointed out by nometreino, as well as the second for the other variable.

Without this code would give an error because nowhere this space has been booked before.

I don’t know details but my understanding is that he will always use one malloc() to do this, which is not always what you want.

This would have the same effect:

int k;
char* nometreino = malloc(101);
char* nometeste = malloc(101);
scanf("%100s[^ ] %100s[^ ] %d", &nometreino, &nometeste, &k);

I put in the Github for future reference.

In fact almost this, because it’s allocating a space probably larger than it needs and if it needs more it has no way to use, but that’s more or less how people use it. Has a response that talks about something more suitable, though it is a naive way of doing (another). in this case probably the malloc()could be replaced by a array in stack.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.