串的赋值操作(C++)

来源:互联网 发布:什么是网络印刷 编辑:程序博客网 时间:2024/05/16 19:02
#include <iostream>#include <malloc.h>using namespace std;typedef struct{    char* ch;    int length;} Str;void Strassign(Str& str,char *ch)//结构体的引用{    cout<<str.ch<<endl;    if(str.ch)        delete(str.ch);    int len=0;    char *c=ch;    //cout<<c[3]<<endl<<endl;    while(*c)  //   \0和NULL都会弹出    {        len++;     //这里的len是不算\0的len        c++;    }    if(len==0)    {        str.ch=NULL;        str.length=0;    }    else    {        str.ch=(char *)malloc(sizeof(char)*(len+1));        c=ch;   //注意要让c指回来        for(int i=0; i<=len; i++)        {            str.ch[i]=*c;            c++;        }        str.length=len;        cout<<str.ch<<endl;    }    return ;}int main(){    Str str;    str.ch="hhahhhh";    Strassign(str,"ahcici");    return 0;}
0 0