用一维数组实现变长字符串

类别:编程语言 点击:0 评论:0 推荐:

    经常看到在结构中定一个1维的数组,估计大多数人初看这种定义都要蒙一下,其实这是用结构实现变长字符串,是程序设计中一个很有意思的技巧
    使用结构实现变长字符串可以很容易的控制字符串的结构,方便对字符串数据的操作。
试想一下,如果不用结构那么需要一位一位的计算每一个字符所在位置,不把你搞死才怪
废话少说,下面是一个例子,很简单的。
#pragma pach(push, 1)
struct SHORT_STRING
{
 BYTE byStrLen;
 char sString[1];
};

struct STRUCT_HEAD
{
 BYTE byRelation;
 bool bNotify;
};
struct STRUCT_HEAD_SAVE : STRUCT_HEAD
{
 SHORT_STRING PartnerName;
};

struct STRUCT_SAVE_HEAD
{
 WORD wCount;
 BYTE byMsgTransmit;
};

#pragma pack(pop)

#define LOGIN_ROLE_NAME_MAX_LEN 32
#define SHORT_STRING_LEN(n) ((n) + 1)
#define STRUCT_HEAD_SAVE_LEN(n) (sizeof(STRUCT_HEAD) + SHORT_STRING_LEN(n))

int main()
{
 int nCount = 10;
 STRUCT_SAVE_HEAD* pSaveHead;
 int nSize = sizeof(STRUCT_SAVE_HEAD) + (sizeof(STRUCT_HEAD_SAVE) + LOGIN_ROLE_NAME_MAX_LEN) * nCount;
 pSaveHead = (STRUCT_SAVE_HEAD*)malloc(nSize);

 int nOffset = sizeof(STRUCT_SAVE_HEAD);
 pSaveHead->wCount = 0;

 STRUCT_HEAD_SAVE* pRelation = (STRUCT_HEAD_SAVE*)(((char*)pSaveHead) + nOffset);
 
 static char szName[][12] = {
  "1",
  "22",
  "333",
  "4444",
  "55555",
  "666666",
  "7777777",
  "88888888",
  "999999999",
  "0000000000"
 };

 for (int i=0; i<10; i++)
 {  
  pRelation->byRelation = 1;
  pRelation->bNotify = 1;
  pRelation->PartnerName.byStrLen = strlen(szName[i]);
  memcpy(pRelation->PartnerName.sString, szName[i], pRelation->PartnerName.byStrLen);
  nOffset += STRUCT_HEAD_SAVE_LEN(pRelation->PartnerName.byStrLen);
  pRelation = (STRUCT_HEAD_SAVE*)(((BYTE*)pSaveHead) + nOffset);
  pSaveHead->wCount++;
 }

 STRUCT_SAVE_HEAD *head = (STRUCT_SAVE_HEAD*)pSaveHead;
 nOffset = sizeof(STRUCT_SAVE_HEAD);
 pRelation = (STRUCT_HEAD_SAVE*)(((char*)pSaveHead) + nOffset);

 pRelation = (STRUCT_HEAD_SAVE*)&(pRelation->PartnerName.sString[pRelation->PartnerName.byStrLen]);
 pRelation = (STRUCT_HEAD_SAVE*)&(pRelation->PartnerName.sString[pRelation->PartnerName.byStrLen]);
 pRelation = (STRUCT_HEAD_SAVE*)&(pRelation->PartnerName.sString[pRelation->PartnerName.byStrLen]);
}

本文地址:http://com.8s8s.com/it/it24131.htm