c Language Simple Problem Questions

Asked 1 years ago, Updated 1 years ago, 292 views

I am a college student who is preparing to return to school after discharge. While preparing for my return to school, I was solving some C language problems, but there was a problem that got stuck while solving them, so I asked a question.

And then str1 and str2 are used to send text messages from the program user It receives input, but it receives input through an fgets function call. Subsequently Copy the string stored in str1 to str3 and save it to str2 Let's add the string after the string stored in str3. And Finally, let's print out the string stored in str3.

For example, strings stored in str1 and str2 are: 같다면, str1 "simple" str2 "string"

Str3 should contain the string "simplestring".

While solving these questions,

#include <stdio.h>

int main(void)
{
    char str1[20];
    char str2[20];
    char str3[40];

    fputs ("String input 1: ", stdout);
    fgets(str1, sizeof(str1), stdin);
    fputs ("String input 2: ", stdout);
    fgets(str2, sizeof(str2), stdin);
    str1[strlen(str1) - 1] = 0;
    str2[strlen(str2) - 1] = 0;
    for (int i = 0; i < strlen(str1); i++)
        str3[i] = str1[i];
    for (int i = 0; i < strlen(str2); i++)
        str3[strlen(str1)+i] = str2[i];
    printf("%s\n", str2);
    printf ("Result of combination: %s", str3);
    return 0;
}

I solved it like this.

조합의 결과 : simplestring儆儆儆儆儆儆儆儆儆儆儆儆儆儆儆儆儆儆string

It came out like this. Why is this weird string attached to the back? I wonder if the margin of str3 comes out like that, and why does the string stick at the end again If I don't use the strncpy function and do it like that, does it come out like this?

c

2022-12-28 13:11

1 Answers

This is the result of the output of the garbage values in str3.

Something like "abc" is called a string literal in C language (also called a C style string in other languages).

In fact, there are four values stored in memory, such as 'a', 'b', 'c', and 0. In some fields, the last zero is also denoted by null characters or '\0'.

The problem is, add str1 and str2 to str3 and write 0 at the endIt's the completion of a normal C-style string. We haven't done that now, and you're just seeing the results of sequentially printing the value of memory until the printf function runs and happens to meet zero with the value of trash in it.

You can add one line below before outputting the printf function.

str3[strlen(str1) + strlen(str2)] = 0;


2022-12-28 22:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.