Why the directly declared string is different from the input string (string insertion problem)

topic description

string insertion StrInsert operation condition: string sscore t exists, 1 I strength (s) + 1. Operation result: the string t is inserted into the first character position of the string s, and the string value of s changes.

sources of topics and their own ideas

Source: data structure on the computer
idea: directly use the pointer to move and assign characters in the character array

related codes

void StrInsert(char * s, int i, const char * t)
{
    if (i<1 || i>StrLength(s) + 1)
    {
        puts("StrInsert");
        return;
    }
    char * p1;
    p1 = s;
    int j;
    p1 = p1 + i - 1;

    for (j = 0; j < StrLength(s) - i + 1; jPP)
        *(p1 + StrLength(s) + StrLength(t) - i - j) = *(p1 + StrLength(s) - i - j);//

    s[StrLength(s) + StrLength(t)] = "\0";

    for (j = 0; j < StrLength(t); jPP)
        *(p1 + j) = t[j];//
}


what result do you expect? What is the error message actually seen?

when the string t has only one character, it is assumed that the string is "d"
. When the string s to be inserted is assigned in the form of char a [20] = "abc";, call this function StrInsert (aline 2, "d") to make a = "adbc"
when the string s to be inserted is assigned as char a [20]; scanf ("% s", a);. Calling this function directly results in a memory read error, and the printed string is similar to "hot."

I hope someone can answer this question. Thank you very much!

C
Nov.05,2021

use debugging to observe and know what the problem is

first of all, in the form of char a [20] = "abc"; , the data in memory is as follows:
0x60fefc: 61 62 63 00 00 00 | 00 00 00
0x60ff0c: 00 00 00 3D 00 00 | 00 80 3f 00 94 ff 60 00
"abc" followed by 17'0'

the second way char a [20]; scanf ("% s", a); , the data in memory goes like this:
0x60fefc: 61 6263 00 b019 4000 | 45 00 00 08 00 00
0x60ff0c: 3D 00 00 00 3D 00 00 | 00 b032 00 94 ff 60 00
there is only one '0screw behind "abc", and then we don't know what it is. <

is the StrLength () function in your program implemented by yourself? When I assume that strlen,strlen ends with'\ 0' as the judgment character, and thus calculates the length
, the following statement is executed in the second way:

    for (j = 0; j < StrLength(s) - i + 1; jPP)
        *(p1 + StrLength(s) + StrLength(t) - i - j) = *(p1 + StrLength(s) - i - j);

after executing * (p1 + 2) = * (p1 + 1) for the first time, the data in memory looks like this:
0x60fefc: 61 62 63 b019 40 00 | 45 00 00 08 00 00
0x60ff0c: 3D 00 00 00 3D 00 00 | 00 b0 32 00 94 ff 60 00
see, the flag'\ 0' at the end of the string is overwritten, and the next time strlen is executed,

Menu