C. A complete beginner's question!!

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

#include <stdio.h>

int main()
    charline[10] = "; <-- Questions about this!!
    int i;

    printf("Enter string ==>");
    scanf("%s", line);         

    for (i = 9; i >= 0; i--)
        printf("%c", line[i]);


When char line[10] = ";, the output is normal Char line [10]; if you enter it like this, why? Does it print out because the price of garbage is attached to the back? What is the difference between the two? Help me!!!!!!!!!!!!!!!


2022-09-20 10:58

1 Answers

char line[10]="abc";

The string is hidden at the end of the string, which is called the null character. NULL, '\0', 0 and so on, but the actual value is 0. Therefore, the behavior of the above code is as follows.


On the other hand, when you initialize an array, some values that you do not specify are automatically initialized to zero. The code above did not specify anything from line[4] to line[9], so they are initialized to zero.

Therefore, charline[10]="; as in the question is the same as putting only null characters in the array as below.


And line[1] to line[9] are automatically initialized to zero because nothing is specified.

If the scanf function is input to the scanf function and the printf is output to %c, then the array's value of 0 is not output to %c.

On the other hand, if you declare an array without initialization, such as charline[10]; without initialization, the array is usually not initialized (especially if it is a local variable) and has the value of the memory as a trash value. This may vary depending on the compiler or system settings. In general, arrays declared as regional variables are not initialized.

Therefore, the value of the uninitialized array compartment is output as %c and the garbage value is visible.

2022-09-20 10:58

If you have any answers or tips

© 2022 pinfo. All rights reserved.