C/C++技巧 多变数据
2023-06-06
7
0
有这样一种情况,我需要存储一个用户的姓名,电话,邮箱等各种信息,各种信息都是字符串,那么该怎么能比较高效且内存的使用比较高了?
我们可以采用偏移计算的方式:
typedef sturct _MY_STURCT
{
int totallen;
int nameoffset;
int addressoffset;
int mailoffset;
}MY_STRUCT,*PMY_STRUCT;
int totallen = sizeof(MY_STURCT) + strlen(pName) + strlen(pAddress) + strlen(pMail);
PMYSTURCT pMy = malloc(totallen );
if(pMy == NULL) return;
pMy->nameoffset = sizeof(MY_STURCT);
pMy->addressoffset = pMy->nameoffset + strlen(pAddress);
pMy-> mailoffset = pMy->addressoffset + strlen(pMail);
PCHAR pName = (PCHAR)pMy + pMy-> nameoffset;
PCHAR pAddress = (PCHAR)pMy + pMy-> addressoffset;
PCHAR pMail = (PCHAR)pMy + pMy-> mailoffset;