您的位置:首页 > 其它

词法分析之动态字符串

2016-10-03 11:38 176 查看
C语言字符串并没有记录系统为其分配的长度,用户必须自己将字符串长度保存在其他变量中,操作不当会产生错误,导致缓存区溢出,于是决定自己定义一个动态字符串数据结构

typedef struct DynString
{
int count;          //字符串长度
int capacity;       //字符串容量
char *data;         //指向字符串的指针
}DynString
/**
总共定义了5个函数,动态字符串的初始化,清空,重置,重新分配容量大小,追加字符
**/
void dynstring_init(DynString *pstr,int initsize)/**初始化,initsize表示分配空间大小**/
{
if(pstr!=NULL)
{
pstr->data=(char *)malloc(sizeof(char)*initsize);
pstr->count=0;
pstr->capacity=initsize;
}
}
void dynstring_free(DynString *pstr)/**清空**/
{
if(pstr!=NULL)
{
if(pstr->data)
free(pstr->data);
pstr->count=0;
pstr->capacity=0;
}
}
void dynstring_reset(DynString *pstr)/**重置,先把字符串清空,再初始化分配8个字符空间大小**/
{
dynstring_free(pstr);
dynstring_init(pstr,8);
}
void dynstring_realloc(DynString *pstr,int new_size)/**重新分配容量大小**/
{
int capacity;
char *data;
capacity=pstr->capacity;
while(capacity<new_size)
{
capacity*=2;
}
data=(char *)realloc(pstr->data,capacity);
if(!data)
error("内存分配失败");/**这个函数需要自己定义,意思是出现错误,并输出里面的字符串,暂时不用管**/
pstr->data=data;
pstr->capacity=capacity;
}
void dynstring_chcat(DynString *pstr,int ch)/**追加字符ch**/
{
int count;
count=pstr->count+1;
if(count>pstr->capacity)
dynstring_realloc(pstr,count);
((char *)pstr->data)[count-1]=ch;
pstr->count=count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编译原理