当前位置: 代码迷 >> C语言 >> 结构体原来还可以这么用 -- 结构体的高级应用 -- 原创安全字符串
  详细解决方案

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

热度:180   发布时间:2005-07-11 13:24:00.0
结构体原来还可以这么用 -- 结构体的高级应用 -- 原创安全字符串

最近研究发现,结构体还可以如同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 <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h>

#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(); }

搜索更多相关的解决方案: 结构体  字符  高级  应用  

----------------解决方案--------------------------------------------------------
C++中的 结构体是一个特殊的类,这个与C中的 结构体不能混淆。
----------------解决方案--------------------------------------------------------
在C编辑器下可以这样写么?
能运行过去?我的TC2。0不行!
如果不能在C编辑器下运行那就不是你说的什么秘密了,而是象KNOCKER所说的在C++中
结构就是特殊的类,唯一的区别就是,在结构中的成员默认是公有的,而类是私有的!你看看,联合也是可以的!
----------------解决方案--------------------------------------------------------
好像TC2无法运行,先前一直使用Dev-C++编译的,没有注意到这一点,经大家的点拨,我明白了许多,谢谢。。
----------------解决方案--------------------------------------------------------
  相关解决方案