c language char line[10] = "; Difference between char line[101];

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

#include <stdio.h>

int main()
{
    char line[10] = "; <-- this and
    int i;

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

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

    printf("\n");
}
#include <stdio.h>

int main()
{
    char line[101]; <-- question about this..!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    int str;

    printf("Enter alphanumeric characters <100 characters or less> :");
    scanf("%s", line);

    printf("Enter string ==> %s\n", line);
    printf("Transformed string ==>");

    str = strlen(line); 

    for (int i = str; i >= 0; i--)
    {
        printf("%c", line[i]);
    }
    printf("\n");

    return 0;
}

No, in the code above, if charline[10] = "; is not attached, the garbage value comes out, but
In the code below, why doesn't the garbage value come out even if you don't put =" like charline[101];?

What's the difference between the two? You have to stick to the frozen one and you don't have to stick to the frozen one. It's so hard.

c

2022-09-20 10:50

1 Answers

for (i = 9; i >= 0; i--)

The above code is that the for loop will spin from 9. If a short string is entered, there is a garbage value at the back of the array, and 9 is the end of the array, so the loop turns and outputs it, including the garbage value.

On the other hand, the code below obtains the length of the string entered through the strlen function and stores it in the str, and the for loop starts from the str, not from the end of the array. str is the length of the string entered, which is the index where the null character of the string is located in the array. Since the index where the null character is located is printed to the beginning of the array, the garbage value is not printed.

    str = strlen(line); 

    for (int i = str; i >= 0; i--)


2022-09-20 10:50

If you have any answers or tips


© 2022 pinfo. All rights reserved.