ch4

串的堆分配存储结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <stdlib.h>
#include <string.h>
int (){
char *a1=NULL;
char *a2=NULL;
a1=(char*)malloc(10*sizeof(char));
strcpy(a1,"abcd");
a2=(char*)malloc(10*sizeof(char));
strcpy(a2,"efgh");//同上
int lengthA1=strlen(a1);//a1的长度
int lengthA2=strlen(a2);//a2的长度
//尝试将合并的串存储在 a1 中,如果 a1 空间不够,则用realloc动态申请
if(lengthA1<lengthA1+lengthA2){
a1=(char*)realloc(a1,(lengthA1+lengthA2+1)*sizeof(char));
}
//合并两个串到 a1 中
for(int i=lengthA1;i<lengthA1+lengthA2;i++){
a1[i]=a2[i-lengthA1];
}
//串的末尾要添加 ,避免出错
a1[lengthA1+lengthA2]='