The problem of using the modifier of scanf function

use modifiers before format characters to specify the width of the input data, such as the following program, the input abcde, wants to output an abcde, but the order in which the character variables are declared makes the results different. what is the reason? I really don"t understand. I hope the bosses will not hesitate to give us advice

-sharp include<stdio.h>

int main(){
    char c1,c2;
    scanf("%3c%2c",&c1,&c2); 
    printf("%c,%c",c1,c2);
    return 0;
} 

input: abcde
output: e

-sharp include<stdio.h>

int main(){
    char c2,c1; // why?
    scanf("%3c%2c",&c1,&c2); 
    printf("%c,%c",c1,c2);
    return 0;
} 

input: abcde
output: a

C
Aug.25,2021

this is related to memory allocation. Local variables are allocated on the stack, and the stack is allocated from high memory to low memory.

< H2 > case 1 < / H2 >

char C1, c2

initial memory

  +-----+
  |     |      +   
  |     |  c1  |
  |     |      |
  +-----+      |
  |     |      |
  |     |  c2  v   
  |     |
  +-----+

read 3 characters to C1 position for the first time

+-------+
|       |
|       |
+-------+
|   c   |
|       |
+-------+
|   b   |
|       |
+-------+
|   a   |  c1
|       | 
+-------+
|       |  c2
|       |
+-------+

read 2 characters to c2 position for the second time

+-------+
|       |
|       |
+-------+
|   c   |
|       |
+-------+
|   b   |
|       |
+-------+
|   e   |  c1
|       | 
+-------+
|   d   |  c2
|       |
+-------+
< H1 > case two < / H1 >

initial memory

  +-----+
  |     |      +   
  |     |  c2  |
  |     |      |
  +-----+      |
  |     |      |
  |     |  c1  v   
  |     |
  +-----+

read 3 characters to C1 position for the first time

+-------+
|       |
|       |
+-------+
|       |
|       |
+-------+
|   c   |
|       |
+-------+
|   b   |  c2
|       | 
+-------+
|   a   |  c1
|       |
+-------+

read 2 characters to c2 position for the second time

+-------+
|       |
|       |
+-------+
|       |
|       |
+-------+
|   e   |
|       |
+-------+
|   d   |  c2
|       | 
+-------+
|   a   |  c1
|       |
+-------+

can be verified by program

-sharpinclude <stdio.h>

int main() {
    char c2 = '1', c1 = '2';
    printf("c2 = %c\n", c2); // c2 1
    scanf("%3c",&c1); 
    printf("c2 = %c\n", c2); // c2 b
    return 0;
} 

  1. you cannot read multiple characters into the memory of one character, otherwise there will be memory coverage problems, which will lead to incorrect program running results or segment errors
  2. if you want to skip some characters, you can use the % * modifier of the scanf function, such as the following code:
-sharpinclude <stdio.h>
int main(void){
    char c1, c2;
    scanf("%c%*2c%c", &c1, &c2); //c1, 2c2
    printf("%c, %c", c1, c2);
    return 0;
}
Menu