Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The scanf function in C language uses a width specifier for char

There is a code where I enter ABCDEFGH and press enter, and the final result is HGF. When I use debug mode to observe variables. When executing the first sentence input, x='A'. After the next step, x='D', y='C'. After the next step, x='H', y='G', z='F'

#include <stdio.h>

int main() {
    char x, y, z;
    scanf("%2c", &x);
    scanf("%3c", &y);
    scanf("%4c", &z);
    printf("%c%c%c", x, y, z);
    return 0;
}

I am currently very confused as to why this is happening. As far as I know, "%3c" means to read in 3 characters, but only store the first one and discard the last two. I'm not sure if there's a problem with this code. Can you explain why the output is like this, regardless of whether the code was written incorrectly or not?

like image 424
Clara Avatar asked Oct 29 '25 03:10

Clara


1 Answers

As explained by @Someprogrammerdude, the code has undefined behavior because you are attempting to store multiple bytes into memory but pass the addresses of single byte variables. Don't worry about this mistake, scanf is one the most misunderstood functions in the C library, many programmers get it wrong.

Here is a modified version that does not have undefined behavior:

#include <stdio.h>

int main(void) {
    char x[2], y[3], z[4];
    if (scanf("%2c%3c%4c", x, y, z) != 3)
        return 1;
    printf("%c%c%c\n", *x, *y, *z);
    return 0;
}

Input: ABCDEFGH and Enter
Output: ACF

Here is an alternative with the same output using the * modifier that prevents the storage of the conversion results:

#include <stdio.h>

int main(void) {
    char x, y, z;
    if (scanf("%c%*c%c%*2c%c%*3c", &x, &y, &z) != 3)
        return 1;
    printf("%c%c%c\n", x, y, z);
    return 0;
}
like image 190
chqrlie Avatar answered Oct 30 '25 17:10

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!