1 #include <stdio.h>
2 #include <stdlib.h>
3 /******************
4 测试将结构体通过memcpy转换为数组的可行性
5 ******************/
typedef struct TEST
{
short a;
short b;
short c;
};
struct TEST1
{
char a;
short b;
int c;
char* d;
};
int main()
{
struct TEST test, test_1;
struct TEST1 test1,test1_1;
char tmp[10];
short buf[10];
char i;
test.a = 0x1A10;
test.b = 0x2B11;
test.c = 0x3C12;
memcpy(buf, &test, sizeof(test));
printf("sizeof(char) = %d\r\n", sizeof(char));
printf("sizeof(short) = %d\r\n", sizeof(short));
printf("sizeof(int) = %d\r\n", sizeof(int));
printf("sizeof(char*) = %d\r\n", sizeof(char*));
printf("sizeof(short*) = %d\r\n", sizeof(short*));
printf("sizeof(int*) = %d\r\n", sizeof(int*));
printf("\r\nsizeof(test) = %d\r\n", sizeof(test));
for(i=0;i<sizeof(test);i++)
{
printf("buf[%d] = %x\r\n", i, buf[i]);
}
printf("------------------\r\n");
memcpy(tmp, &test, sizeof(test));
for(i=0;i<sizeof(test)+2;i++)
{
printf("tmp[%d] = %x\r\n", i, tmp[i]);
}
printf("--back--\r\n");
memcpy(&test_1,tmp, sizeof(test));
printf("test_1.a = %x\r\n", test.a);
printf("test_1.b = %x\r\n", test.b);
printf("test_1.c = %x\r\n", test.c);
printf("------------------\r\n");
printf("sizeof(test1) = %d\r\n", sizeof(test1));
test1.a = 0x11;
test1.b = 0x1203;
test1.c = 0x13243567;
test1.d = "ABC";
memcpy(buf, &test1, sizeof(test1));
for(i=0;i<sizeof(test1);i++)
{
printf("buf[%d] = %x\r\n", i, buf[i]);
}
printf("--back--\r\n");
memcpy(&test1_1,buf, sizeof(test1));
printf("test1_1.a = %x\r\n", test1_1.a);
printf("test1_1.b = %x\r\n", test1_1.b);
printf("test1_1.c = %x\r\n", test1_1.c);
printf("test1_1.d = %s\r\n", test1_1.d);
printf("------------------\r\n");
memcpy(tmp, &test1, sizeof(test1));
for(i=0;i<sizeof(test1);i++)
{
printf("tmp[%d] = %x\r\n", i, tmp[i]);
}
return 0;
}
运行结果:
sizeof(char) = 1
sizeof(short) = 2
sizeof(int) = 4
sizeof(char*) = 4
sizeof(short*) = 4
sizeof(int*) = 4
sizeof(test) = 6
buf[0] = 1a10
buf[1] = 2b11
buf[2] = 3c12
buf[3] = ffffcccc
buf[4] = ffffcccc
buf[5] = ffffcccc
------------------
tmp[0] = 10
tmp[1] = 1a
tmp[2] = 11
tmp[3] = 2b
tmp[4] = 12
tmp[5] = 3c
tmp[6] = ffffffcc
tmp[7] = ffffffcc
--back--
test_1.a = 1a10
test_1.b = 2b11
test_1.c = 3c12
------------------
sizeof(test1) = 12
buf[0] = ffffcc11
buf[1] = 1203
buf[2] = 3567
buf[3] = 1324
buf[4] = 2f6c
buf[5] = 42
buf[6] = ffffcccc
buf[7] = ffffcccc
buf[8] = ffffcccc
buf[9] = ffffcccc
buf[10] = 1a10
buf[11] = 2b11
--back--
test_1.a = 1a10
test_1.b = 2b11
test_1.c = 3c12
------------------
tmp[0] = 11
tmp[1] = ffffffcc
tmp[2] = 3
tmp[3] = 12
tmp[4] = 67
tmp[5] = 35
tmp[6] = 24
tmp[7] = 13
tmp[8] = 6c
tmp[9] = 2f
tmp[10] = 42
tmp[11] = 0
结论,同一系统可行,
工作中几个内部模块自己用的消息收发可以使用