C. A complete beginner's question!!

Asked 2 years ago, Updated 2 years ago, 146 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]);
    }

    printf("\n");
}

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!!!!!!!!!!!!!!!

char

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.

line[0]='a';
line[1]='b';
line[2]='c';
line[3]=0;

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.

line[0]=0;

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


© 2024 OneMinuteCode. All rights reserved.