串和串的賦值操作


1.串的存儲結構

typedef struct{
    char str[MaxSize+1];//末尾+'\0' 
    int length;
}Strfix;
//變長存儲結構 
typedef struct{
    char *ch;
    int length;
}StrNonfix;
    StrNonfix S;
    S.length=10;
    S.ch=(char*)malloc((S.length+1)*sizeof(char));
    S.ch[8]='J';
    cout<<S.ch[8]<<endl;
    free(S.ch);//free函數是free首地址,malloc給的就是首地址 

2.串的賦值操作

int strAssign(StrNonfix& str,char* ch){
    //釋放原有的內容 
    if(str.ch){
        free(str.ch); 
    } 
    int len=0;
    char *c=ch;
    //確定賦值目標串的長度 
    //遇到'\0'就結束 
    while(*c){
        ++len;
        ++c;
    }
    //目標字符串沒有除'\0'以外的字符 
    if(len == 0){
        str.ch=NULL;
        str.length=0;
        return 1;
    }else{
        str.ch=(char*)malloc(sizeof(char)*(len+1));
        //分配失敗
        if(str.ch == NULL){
            return 0;
        }else{
            c=ch;
            //len+1次把'\0'賦值過去 
            for(int i=0;i<=len;++i,++c){
                str.ch[i]=*c;
            }
            str.length=len;
            return 1; 
        }
         
    }
     
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM