Some questions about assigning values to variables and arrays in C language

This article is some error-prone areas when I first learned C language, so I recorded it.
It should be helpful for students who are new to C language.

1. Scanf absorbs carriage returns when inputting characters

Let’s start with the following question

ASCII sorting

After inputting three characters, output the three characters in the order of ASCII code of each character from small to large.

Input

There are multiple groups of input data, each group occupies one line and consists of three characters without spaces.

Output

For each group of input data, one line is output, and the characters are separated by a space.

Sample Input

qwe
asd
zxc

Sample Output

e q w
a d s
c x z

Code

#include <cstdio>
#include <algorithm>
using namespace std;

int main(void)
{
    
    
    char a[3];
    while (scanf("%c%c%c", &a[0], &a[1], &a[2]) != EOF) {
    
    
        getchar();
        sort(a, a + 3);
        printf("%c %c %c\n", a[0], a[1], a[2]);
    }
    
    return 0;
}

When doing this problem, it is easy to ignore the getchar() on line 9, then you will find that the output is a bit strange.

Explanation of scanf() and getchar()

  1. When reading keyboard data in C language, it is generally data input with a buffer, and you need to press the Enter key to complete the input confirmation of the "line" data. ① Scanf() will automatically ignore the preceding blank characters when reading value data or character strings (blank characters refer to: carriage return, space, TAB key), that is, start reading from the first non-blank character and encounter a blank again The character ends the input of this type of data. ② When scanf() reads character data, blank characters will also be read.

  2. In the 8th line of code, there are three scanf() functions that read characters. The carriage return character at the end of the input "eqw" in the first line will remain in the input buffer. Therefore, the carriage return will be read when the next "character" operation function (getchar(), scanf("%c"), gets(), etc.) is run.

  3. Therefore, whether scanf() must be followed by a getchar() to absorb carriage returns depends on the type of the next input data. If it is a character-reading operation, there are many ways to deal with it.

  4. As for the scanf() function, it is worthy of our in-depth understanding.

2. The'\0' at the end of the string

We also start to introduce from the following topics

Binary conversion

Input
input an integer n, (-2^31 <n <2^31)

Output
converts n into the corresponding binary number, and outputs the converted binary length and binary number sequence

Sample Input
5

Sample Output
101

Code

The basic idea is to use short division to find the remainder of 2 each time, store it in an array, and finally output in reverse order as a binary number

Initial error code

#include <stdio.h>
#include <string.h>

int main(void)
{
    
    
    int n, len, i = 0;
    char a[50];
    
    scanf("%d", &n);
    while(n != 0){
    
     
        a[i++] = n % 2 + '0';
        n /= 2;
    }
    len = strlen(a);
    printf("二进制数长度:%d\n", len);
    printf("二进制数:");
    for (i = len - 1; i >= 0; i--)
    	printf("%c", a[i]);
    puts("");
    
    return 0;
}

The output when entering 5:
Insert picture description here

Some explanations of strlen() and printf("%s",)

  1. Run the above code, you will find that the output len ​​is greater than the actual length, and the output binary number is also garbled.
  2. Because gets() or scanf("%s", str) will automatically add'\0' to the end of str after the end of input, and if a single character is assigned like the above, there is no'\0' at the end of str.
  3. The parameter of the function strlen() must be a string, strlen judges the end of the string based on'\0', so when the end is not 0, the memory outside str will be read to make the value of len greater than the actual The value of the string, thus outputting garbled characters.
  4. Use printf("%s\n", str); the same is true when outputting str. It will read character by character until it reaches'\0', but there is no'\0 at the end of str. ', it will read the memory other than str and output garbled characters.
  5. Solution: ①Open the array directly outside the main function, the array will all be initialized to 0 ②Because the ASCII code of'\0' is 0, we can change the 7th line to char a[50]={0} ; This will initialize each element to 0.

Solution①

#include <stdio.h>
#include <string.h>

char a[50];

int main(void)
{
    
    
    int n, len, i = 0;
    
    scanf("%d", &n);
    while(n != 0){
    
     
        a[i++] = n % 2 + '0';
        n /= 2;
    }
    len = strlen(a);
    printf("二进制数长度:%d\n", len);
    printf("二进制数:");
    for (i = len - 1; i >= 0; i--)
    	printf("%c", a[i]);
    puts("");
    
    return 0;
}

Insert picture description here

Solution ②

#include <stdio.h>
#include <string.h>

int main(void)
{
    
    
    int n, len, i = 0;
    char a[50] = {
    
    0};
    
    scanf("%d", &n);
    while(n != 0){
    
     
        a[i++] = n % 2 + '0';
        n /= 2;
    }
    len = strlen(a);
    printf("二进制数长度:%d\n", len);
    printf("二进制数:");
    for (i = len - 1; i >= 0; i--)
    	printf("%c", a[i]);
    puts("");
    
    return 0;
}

Insert picture description here

Later improved writing method, directly use len as a subscript to record the length of the array

#include <stdio.h>
#include <string.h>

int main(void)
{
    
    
    int n, len = 0, i;
    char a[50];
    
    scanf("%d", &n);
    while(n != 0){
    
     
        a[len++] = n % 2 + '0';
        n /= 2;
    }
    
    printf("二进制数长度:%d\n", len);
    printf("二进制数:");
    for (i = len - 1; i >= 0; i--)
    	printf("%c", a[i]);
    puts("");
    
    return 0;
}

3. The initial assignment of C language to the array has the following provisions

  1. You can only assign initial values ​​to some elements. When the number of values ​​in {} is less than the number of elements, only the previous part of the elements is assigned. For example: int a[10]={0,1,2,3,4}; means that only 5 elements of a[0]~a[4] are assigned, and the next 5 elements are automatically assigned a value of 0.
  2. You can only assign values ​​to the elements one by one, not the entire array. For example, to assign 1 value to all ten elements, it can only be written as: int a
    [10]={1,1,1,1,1,1,1,1,1,1}; but cannot be written as: int a [10]=1;
  3. If you assign values ​​to all elements, the number of array elements may not be given in the array description. For example: int a[5]=
    {1,2,3,4,5}; can be written as: int a[]={1,2,3,4,5}; dynamic assignment can be in the process of program execution, Dynamically assign
    values to the array . At this time, the loop statement can be used with scanf function to assign values ​​to the array elements one by one.

4. For uninitialized arrays

  1. For local arrays:
    ① int a[100]; This writing method is not initialized, so 100 elements are all machine garbage values;
    ② int a[100] = {0, 2, 3}; This writing method first 3 Each element is initialized to 0, 2, 3, and the rest are set to 0;
    ③ int a[100] = {0}; This writing method initializes all 100 elements to 0.
  2. For arrays that are global or modified as static properties:
    if initialized, it is the same as above ②, ③; if not initialized, all elements are automatically set to 0.

5. For variables that are not initialized

  1. Only global variables and static variables will be automatically initialized to 0.

  2. Ordinary local variables, if not initialized, are random data.

Guess you like

Origin blog.csdn.net/weixin_43772166/article/details/88556177