#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct HString {
char *ch=NULL; //需要初始化
int length=0;
}HString;
void hsAssign(HString &T,char s[]) {
if (T.ch)
free(T.ch);
T.ch = (char*)malloc(sizeof(char));
if (!T.ch) {
printf("Fail to create the string.");
return;
}
T.length = strlen(s);
for (int i = 0; i < strlen(s); i++)
T.ch[i] = s[i];
}
int hsCompare(HString T, HString S) {
//若S>T,则返回值>0
for (int i = 0; i < T.length&&i < S.length; i++)
if (T.ch[i] != S.ch[i])
return S.ch[i] - T.ch[i]; //返回的是ASCII码的差
return S.length - T.length;
}
int hsClear(HString &T) {
free(T.ch);
T.ch = NULL;
T.length = 0;
return 1;//确认清空串操作是否成功
}
void hsConcat(HString &con, HString T, HString S) {
if (con.ch)
free(con.ch);
con.ch = (char*)malloc(sizeof(char));//确保con被分配了新的存储空间
for (int i = 0; i < T.length; i++)
con.ch[i] = T.ch[i];
for (int i = T.length; i < T.length + S.length; i++)
con.ch[i] = S.ch[i - T.length];
con.length = T.length + S.length;
}
void hsSub(HString &sub, HString T, int pos, int len){
if (pos -1> T.length || pos <= 0 || pos + len -1> T.length || len < 0) {
printf("Wrong input.");
return;
}
int count = 0;
if (sub.ch)
free(sub.ch);
sub.ch = (char*)malloc(sizeof(char));
for (int i = pos - 1; i <=pos + len - 2; i++)
sub.ch[count++] = T.ch[i];
sub.length = len;
}
void hsInsert(HString &S, int pos, HString T) {
int count = 0;
if (pos <= 0 || pos - 1 > S.length) {
printf("Wrong input");
return;
}
for (int i = S.length - 1; i >= pos - 1; i--)
S.ch[i + T.length] = S.ch[i];
for (int i = pos - 1; i <= pos + T.length - 2; i++)
S.ch[i] = T.ch[count++];
S.length += T.length;
}
void hsPrint(HString T) {
for(int i=0;i<T.length;i++)
printf("%c", T.ch[i]);
}
int main() {
HString T, S1,S2;
char s[20];
scanf_s("%s", s, 20);
hsAssign(S1, s);
scanf_s("%s", s, 20);
hsAssign(S2, s);
hsInsert(S1, 2, S2);
hsPrint(S1);
return 0;
}
在hsInsert()函数中如果使用了S.ch=(char*)realloc(S.ch,(T.length+S.length)*sizoef(char));
结果是tTEST
而如果不用realloc()函数 结果是tTESTest
请问这是为什么?