堆分配顺序串的类型定义
typedef struct{
char *ch;
int length;
}HString;
//将串常量chars赋值给堆分配的顺序串S
void StrAssign_HS(HString &S,char chars[]){
int i = 0;
int chars_length = 0;
while(chars[i]!='\0'){//求chars长度
++i;
++chars_length;
}
if(S.ch) delete S.ch;//如果S已经存在,将释放S所占空间
if(!chars_length){//如果chars[]的长度为0,则S.ch = NULL,S.length = 0
S.ch = NULL;
S.length = 0;
}
else{
S.ch = new char[chars_length];
if(!S.ch){cout<<"空间申请失败\n";}
int j = 0;
int k = 0;
while(k<chars_length)S.ch[k++] = chars[j++];
S.length = chars_length;
}
}
网友评论