Guard scanf from reading too many characters using definition?

I usually use the definition for string size, but when I use scanf(), I want to protect the function from reading too many characters (and reserve space for the null terminator). I was wondering if I can do this using my define, and not a hard-coded magic number ...

#include <stdio.h>

#define MAXLEN 4

int main(void) {
    char a[MAXLEN];
    scanf("%3s", a); // Can I do that with 'MAXLEN' somehow?
}

Is it possible? If so, how?

+4
source share
1 answer

Used to determine:

#define LENSTR_(x) #x
#define LENSTR(x) LENSTR_(x)

then you can use:

#define MAXLEN 3

char a[MAXLEN + 1];
scanf("%" LENSTR(MAXLEN) "s", a);
+9
source

Source: https://habr.com/ru/post/1685801/


All Articles