C实现串赋值时的小问题,望解惑
下面是实现StrAssigns()函数的源码:
#define ERROR 0#define OK 1typedef int Status;typedef struct{ char *ch; int length;}HString;Status StrAssigns(HString *T, char *chars){ int i,length = 0; char *c = chars; //if(T->ch != NULL)free(T->ch); for(i = 0; c[i] != '\0'; i++)length++; if(length == 0) { T->ch = NULL; T->length = 0; return OK; } T->ch = (char *)malloc(length * sizeof(char)); if(!T->ch)return OVERFLOW; else { for(i = 0; i< length; i++) T->ch[i] = chars[i]; T->length = length; } return OK;}int main(void){ HString S; StrAssigns(&S,"abc"); printf("%s",S.ch); }
#include<stdio.h>#include<stdlib.h>#define ERROR 0#define OK 1#define OVERFLOW 0typedef int Status;typedef struct{ char *ch; int length;}HString;Status StrAssigns(HString *T, char *chars){ int i,length = 0; char *c = chars; //if(T->ch != NULL)free(T->ch); for(i = 0; c[i] != '\0'; i++) length++; if(length == 0) { T->ch = NULL; T->length = 0; return OK; } T->ch = (char *)malloc(length * sizeof(char)+1); //增加个 字节单元 来存放字符串的结束符 if(!T->ch) return OVERFLOW; else { for(i = 0; i< length; i++) T->ch[i] = chars[i]; T->ch[i]=chars[i]; //字符串的结束符 T->length = length; } return OK;}int main(void){ HString S; StrAssigns(&S,"abc"); printf("%s",S.ch); }