TLV可变结构体
代码
1 #include <stdio.h>
2 #include <malloc.h>
3 #include <string.h>
4
5 typedef unsigned char UCHAR;
6 typedef char CHAR;
7 typedef unsigned long ULONG;
8 typedef unsigned int USHORT;
9 #include <stdio.h>
10 #include <string.h>
11
12
13
14 typedef struct STRUCT_TLV
15 {
16 USHORT usType;
17 USHORT usLen;
18 UCHAR ucValue[0];
19 }TLV;
20
21 int main()
22 {
23 UCHAR *pdata = NULL;
24 TLV * pstTLV = NULL;
25 const CHAR * p1 = "ab";
26 const CHAR * p2 = "cde";
27
28 printf("sizeof(TLV)=%d", sizeof(TLV));
29
30 pdata = (UCHAR *)malloc(2 * (sizeof(TLV) + sizeof(UCHAR))); /*此处虽然没按照所用空间申请,但结果正确,建议不这样做*/
2 #include <malloc.h>
3 #include <string.h>
4
5 typedef unsigned char UCHAR;
6 typedef char CHAR;
7 typedef unsigned long ULONG;
8 typedef unsigned int USHORT;
9 #include <stdio.h>
10 #include <string.h>
11
12
13
14 typedef struct STRUCT_TLV
15 {
16 USHORT usType;
17 USHORT usLen;
18 UCHAR ucValue[0];
19 }TLV;
20
21 int main()
22 {
23 UCHAR *pdata = NULL;
24 TLV * pstTLV = NULL;
25 const CHAR * p1 = "ab";
26 const CHAR * p2 = "cde";
27
28 printf("sizeof(TLV)=%d", sizeof(TLV));
29
30 pdata = (UCHAR *)malloc(2 * (sizeof(TLV) + sizeof(UCHAR))); /*此处虽然没按照所用空间申请,但结果正确,建议不这样做*/
31 if (pdata == NULL)
32 {
33 return 0;
34 }
35
36 pstTLV = (TLV *)pdata;
37
38 pstTLV->usType = 0x01;
39 pstTLV->usLen = strlen(p1) + 1;
40 memcpy((void *)pstTLV->ucValue, (void *)p1, pstTLV->usLen);
41 printf("\r\n TLV1:"
42 "\r\n usType=%u"
43 "\r\n usLen=%u"
44 "\r\n ucValue=%s\r\n",
45 pstTLV->usType, pstTLV->usLen, pstTLV->ucValue);
46
47 pstTLV++;
48 pstTLV->usType = 0x02;
49 pstTLV->usLen = strlen(p2) + 1;
50 memcpy((void *)pstTLV->ucValue, (void *)p2, pstTLV->usLen);
51
52 printf("\r\n TLV2:"
53 "\r\n usType=%u"
54 "\r\n usLen=%u"
55 "\r\n ucValue=%s\r\n",
56 pstTLV->usType, pstTLV->usLen, pstTLV->ucValue);
57
58
59 return 0;
60 }
61
32 {
33 return 0;
34 }
35
36 pstTLV = (TLV *)pdata;
37
38 pstTLV->usType = 0x01;
39 pstTLV->usLen = strlen(p1) + 1;
40 memcpy((void *)pstTLV->ucValue, (void *)p1, pstTLV->usLen);
41 printf("\r\n TLV1:"
42 "\r\n usType=%u"
43 "\r\n usLen=%u"
44 "\r\n ucValue=%s\r\n",
45 pstTLV->usType, pstTLV->usLen, pstTLV->ucValue);
46
47 pstTLV++;
48 pstTLV->usType = 0x02;
49 pstTLV->usLen = strlen(p2) + 1;
50 memcpy((void *)pstTLV->ucValue, (void *)p2, pstTLV->usLen);
51
52 printf("\r\n TLV2:"
53 "\r\n usType=%u"
54 "\r\n usLen=%u"
55 "\r\n ucValue=%s\r\n",
56 pstTLV->usType, pstTLV->usLen, pstTLV->ucValue);
57
58
59 return 0;
60 }
61
pdata = (UCHAR *)malloc(2 * (sizeof(TLV) + sizeof(UCHAR))); /*此处虽然没按照所用空间申请,但结果正确,建议不这样做*/
虽然后面的操作越界,但结果还是对的,不知为什么。
但最好还是按照实际所用申请。
pdata = (UCHAR *)malloc(2 * sizeof(TLV) + 3 * sizeof(UCHAR)+ 4 * sizeof(UCHAR));