strcat 儆

Asked 2 years ago, Updated 2 years ago, 47 views

The strcat function is implemented and executed, but < is attached to the end. What's wrong? Oh, I shouldn't write scanf_s in the array. Why is that?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int strlen(char* a)
{
    int i=0;
    while (a[i] != '\0')
        i++;
    return i;
}
void strcat(char* b, char* c)
{
    int n = strlen(b), i;
    for (i = n; i < n + strlen(c); i++)
        b[i] = c[i - n];
}

int main(void)
{
    char s[50], e[50];
    scanf("%s", s);
    scanf("%s", e);
    printf("%d\n", strlen(s));
    printf("%d\n", strlen(e));
    strcat(s, e);
    printf("%s\n", s);
    return 0;
}

strcat c

2022-09-20 16:01

1 Answers

In c language, the string is implemented as a null-terminated-string. Put the characters in the array of char in order to announce the end, put null (0x00) after the last letter.

The strcat implemented by the current questioner puts one letter of the e array in the back of the s array as a for statement, but does not include null that tells you the end. So, I don't know the last one.

If you're lucky, the back of the s is already filled with 0x00, so it won't be a problem if you don't tell us the last time, but the memory we use is not always filled with 0x00. Therefore, you must add one more 0x00 at the end of strcat implemented by the questioner.

< is just a garbage price, but it's fun to understand why this text comes out.

< is a cp949 encoding character that corresponds to the 0xcccccc value. It's a very pretty value to just call it a trash value, and the reason why it's included is because when you build a debug in the Visual Studio, you fill the array of stack variables with 0xcc.

char s[50], e[50];

This means that the memory caught with s will contain 50 0xcc. (When it's a release build, we'll fill it with 0x00) That's why the characters in the back are filled with 0xcc characters when you don't finish null in the questioner's code, which is printed continuously in the Korean window environment.


2022-09-20 16:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.