C++不定长字符串比较合理且简单的解决方法
C++不定长字符串比较合理且简单的解决方法// testrealloc.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define XString_LENGTH 1024 // 默认缓存区的长度www.
class XString
{
char *m_x;
unsigned int m_size;
public:
XString();
~XString();
unsigned int GetSize();
unsigned int GetData(char *&pData);
bool AddData(char *pData, unsigned int nLen);
};
XString::XString()
{
m_size = 0;
m_x = (char*)malloc(XString_LENGTH);
}
XString::~XString()
{
if (m_x)
{
free(m_x);
m_x = NULL;
}
}
unsigned int XString::GetSize()
{
return m_size;
}
unsigned int XString::GetData(char * &pData)
{
pData = (char*)malloc(m_size+1);
if (!pData)
return 0;
memcpy(pData, m_x, m_size);
pData[m_size] = NULL;
return m_size+1;
}
bool XString::AddData(char *pData, unsigned int nLen)
{
if (nLen <= 0)
return false;
if (! pData)
return false;
unsigned nOldSize = m_size;
m_size += nLen;
if (m_size > XString_LENGTH)
{
// int n = m_size - XString_LENGTH;
char *p = m_x;
m_x = (char*)realloc(m_x, m_size);
if (!m_x)
{
m_x = p;
return false;
}
memcpy(m_x+nOldSize, pData, nLen);
// m_x[m_size]=NULL;
// printf("%s-%d\n", m_x, m_size);
// getchar();
}
else
{
memcpy(m_x+nOldSize, pData, nLen);
}
return true;
}
void k() // www.
{
XString a;
for (int i=0; i<3000; i++)
{
if (! a.AddData("88888888", 8))
{
printf("add data failed.\n");
}
}
getchar();
}
int main(int argc, char* argv[])
{
for(int i=0; i<100; i++)
{
k();
}
getchar();
return 0;
}