#include "stdio.h"
#include "stdlib.h"
typedef struct
{
char *ch;
int length;
}Str;
int strassign(Str& str,char* ch)
{
if(str.ch)
free(str.ch);
int len=0;
char *c=ch;
while(*c)
{
++len;
++c;
}
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;
for(int i=0;i<=len;++i,++c)
str.ch[i]=*c;
str.length=len;
return 1;
}
}
}
void main()
{
Str str;
strassign(str,"cur");
printf("helloworld");
}
因为你主程序里ch没有 = NULL 初始化,所以这里是随机值,所以if成立,但是显然这里不能free
if(str.ch)
free(str.ch);
if(str.ch==NULL) 你写为了 if(str.ch=NULL)
#include "stdio.h"
#include "stdlib.h"
typedef struct
{
char *ch;
int length;
}Str;
int strassign(Str& str,char* ch)
{
if(str.ch)
free(str.ch);
int len=0;
char *c=ch;
while(*c)
{
++len;
++c;
}
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;
for(int i=0;i<=len;++i,++c)
str.ch[i]=*c;
str.length=len;
return 1;
}
}
}
int main()
{
Str str;
strassign(str,"cur");
printf("%s", str.ch);
return 0;
}