串的堆分配存储的连接代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 20
#define FALSE 0
#define TRUE 1
#define OK 1
#define ERROR 0
typedef int Status;
typedef struct{
char *ch;
int length;
}HString;
Status StrAssign(HString *S,char *chars)
{
if(S->ch)S->ch=NULL;
int i,j;
i=strlen(chars);//计算长度
if(!i)
{
S->ch=NULL;
S->length=0;
}
else
{
if(!(S->ch=(char *)malloc(i*sizeof(char))))
{
exit(0);
}
else{
for(j=0;j<i;j++){
S->ch[j]=chars[j];
}
S->length=i;
}
}
return OK;
}
Status Concat(HString *S,HString S1,HString S2)
{
int i,j;
if(S->ch)S->ch=NULL;
if(!(S->ch=(char *)malloc((S1.length+S2.length)*sizeof(char))))exit(0);
for(i=0;i<S1.length;i++){
S->ch[i]=S1.ch[i];
}
S->length=S1.length+S2.length;
for(j=S1.length,i=0;j<S->length;j++)
{
S->ch[j]=S2.ch[i];
i++;
}
return OK;
}
void print(HString S)
{
int i;
for(i=0;i<S.length;i++)
{
printf("%c",S.ch[i]);
}
}
Status main()
{
HString S,S1,S2;
char ch1[]="william";
char ch2[]="bao";
StrAssign(&S1,ch1);
StrAssign(&S2,ch2);
Concat(&S,S1,S2);
print(S);
return 0;
}
运行结果如下: