#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "cstring"
using namespace std;
int main() {
char cc[8];//在栈上分配8字节的内存空间
//把cc的内存空间用于字符串。
strcpy(cc, "hello");
cout << "cc=" << cc << endl << endl;
//把cc的内存空间用于int型整数。
// int*a,*b;
// a=(int *)cc;//前4个字节的空间用于整数a。
// b=(int *)cc+4;//后4个字节的空间用于整数b。
// *a=12345;
// *b=54321;
// cout<<"*a="<<*a<<endl;
// cout<<"*b="<<*b<<endl<<endl;
//把cc的内存空间用于结构体
struct stt {
int a;
char b[4];
} *st;
st = (struct stt *) cc;
st->a = 38;
strcpy(st->b, "abc");
cout << "st->a=" << st->a << endl;
cout << "st->b=" << st->b << endl;
int* cc1=(int *) malloc(8);
struct st_girl
{
int bh;
char name[30];
bool yz;
double weight;
string memo;
}girl;
cout<<"超女结构体的大小:"<<sizeof(struct st_girl)<<endl;
string buffer;//创建一个空的string容器buffer
//生成10名超女的信息,存了buffer中
for (int ii = 1; ii <=10 ; ++ii) {
memset(&girl,0,sizeof(struct st_girl));
girl.bh=ii;
sprintf(girl.name,"西施%02d",ii);
girl.yz= true;
girl.weight=48.5+ii;
girl.memo="中国历史第一美女。";
//把超女结构最加到buffer中。
buffer.append((char *)&girl,sizeof (struct st_girl));
}
cout<<"buffer.capacity()="<<buffer.capacity()<<endl;
cout<<"buffer。size()="<<buffer.size()<<endl;
for (int ii = 0; ii < buffer.size()/sizeof(struct st_girl); ++ii) {
memset(&girl,0,sizeof (struct st_girl));
//把容器中的数据复制到超女结构体。
memcpy(&girl,buffer.data()+ii* sizeof (struct st_girl),sizeof (struct st_girl));
//buffer.copy((char*)&girl,sizeof(struct st_girl),ii* sizeof(struct st_girl));
//显示超女结构体成员的值。
cout<<"bh="<<girl.bh<<",name="<<girl.name<<",yz="<<girl.yz<<",weight="<<girl.weight<<",memo="<<girl.memo<<endl;
}
}
输出:
cc=hello
st->a=38
st->b=abc
超女结构体的大小:80
buffer.capacity()=1280
buffer。size()=800
bh=1,name=西施01,yz=1,weight=49.5,memo=中国历史第一美女。
bh=2,name=西施02,yz=1,weight=50.5,memo=中国历史第一美女。
bh=3,name=西施03,yz=1,weight=51.5,memo=中国历史第一美女。
bh=4,name=西施04,yz=1,weight=52.5,memo=中国历史第一美女。
bh=5,name=西施05,yz=1,weight=53.5,memo=中国历史第一美女。
bh=6,name=西施06,yz=1,weight=54.5,memo=中国历史第一美女。
bh=7,name=西施07,yz=1,weight=55.5,memo=中国历史第一美女。
bh=8,name=西施08,yz=1,weight=56.5,memo=中国历史第一美女。
bh=9,name=西施09,yz=1,weight=57.5,memo=中国历史第一美女。
bh=10,name=西施10,yz=1,weight=58.5,memo=中国历史第一美女。
发表回复