词法分析之动态字符串
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; }
相关文章推荐
- 动态生成的字符串输出xml文件并下载
- .net中实现运行时从字符串动态创建对象
- 存储过程里动态生成包含SQL语句字符串
- 如何用SQL动态截取字符串的长度?
- 关于动态数组、静态数组转换为字符串的一些问题 - 给 "厨师" 的回复
- .net中实现运行时从字符串动态创建对象
- 通过字符串变量动态打开窗体并动态调用其方法
- .net中实现运行时从字符串动态创建对象
- 关于CComboBox动态插入字符串
- 实现运行时从字符串动态创建对象
- 在.NET上如何根据字符串动态创建控件
- 词法分析(字符串分析)
- c# vd2005 动态分配字符串数组大小问题,用ArrayList
- 在.NET上如何根据字符串动态创建控件
- 如何安全动态格式化字符串
- .net中实现运行时从字符串动态创建对象 (转)
- 在.NET上如何根据字符串动态创建控件
- .net中实现运行时从字符串动态创建对象
- 不按先后顺序比较字符串序列是否相同(动态SQL)
- 动态字符串数组