c语言结构体字符串成员的删除,结构体原来还可以这么用 -- 结构体的高级应用 -- 原创安全字符串...

结构体原来还可以这么用 -- 结构体的高级应用 -- 原创安全字符串

最近研究发现,结构体还可以如同C++类一样构造使用,一时心血来潮写了个安全字符串结构,大家来看看,也请各位高手指点不足,谢谢啦。。

/* string.h */

#ifndef __STRING_H

#define __STRING_H

#include "string.cpp"

#endif

/* string.cpp */

typedef enum {FALSE=0,TRUE=1} BOOL;

typedef struct safe_string

{

/* variable */

char *contents;

int buffer_size;

/* construction */

void initalize(void);

/* member function */

void buf_allocate(int);

void buf_reallocate(int);

void buf_release(void);

BOOL autostring(const char *);

BOOL getstring(const char *);

int getlength(void);

/* destory */

void destory(void);

} string;

void safe_string::initalize(void)

{

contents=NULL;

buffer_size=0;

}

void safe_string::buf_allocate(int bufsize)

{

destory();

contents=(char *)malloc(bufsize);

if(!contents)

{

printf("No memory for allocating a new string!\n");

printf("Press any key to exit.\n");

getch();

exit(1);

}

buffer_size=bufsize;

}

void safe_string::buf_reallocate(int bufsize)

{

if(!contents)

contents=(char *)malloc(bufsize);

else

contents=(char *)realloc(contents,bufsize);

if(!contents)

{

printf("No memory for reallocating a new string!\n");

printf("Press any key to exit.\n");

getch();

exit(1);

}

buffer_size=bufsize;

}

void safe_string::buf_release(void)

{

int len=getlength();

contents=(char *)realloc(contents,len+1);

if(!contents)

{

printf("No memory for reallocating a string!\n");

printf("Press any key to exit.\n");

getch();

exit(1);

}

buffer_size=len+1;

}

BOOL safe_string::autostring(const char *s)

{

if(!s) return FALSE;

int len=strlen(s);

buf_allocate(len+1);

strcpy(contents,s);

return TRUE;

}

BOOL safe_string::getstring(const char *s)

{

if(!s) return FALSE;

if(!contents) return FALSE;

int len=strlen(s);

if(len+1>buffer_size)

return FALSE;

else

{

strcpy(contents,s);

return TRUE;

}

}

int safe_string::getlength(void)

{

char *p=contents;

int len=0;

while(*p++) len++;

return len;

}

void safe_string::destory(void)

{

if(contents) free(contents);

}

/* debug_string.cpp */

#include

#include

#include

#include

#include "string.h"

int main()

{

string s;

s.initalize();

s.autostring("Hello,world");

printf("%s,%d,%d\n",s.contents,s.buffer_size,s.getlength());

s.destory();

getch();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值