C++变长结构体使用方法


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define HexPrint(_buf, _len) \
{\
    int _m_i = 0;\
    char *_m_buf = (char *)(_buf);\
    int _m_len = (int)(_len);\
    printf("[%s:%d] \r\n", __FUNCTION__, __LINE__);\
    printf("*****************************\n");\
    for(_m_i = 0; _m_i < _m_len; _m_i++)\
    {\
        printf("\033[32m%02x \033[0m", _m_buf[_m_i] & 0xff);\
        if(!((_m_i+1) % 10)) printf("\n");\
    }\
    printf("\nsize = %d\n*****************************\n", _m_len);\
}
using namespace std;


typedef struct Date
{
    int id;
    int age;
    char name[0];
    int grade;
}date;


int main()
{
    date *d = NULL;
    srand((unsigned)time(NULL));
    int size = rand() % 128 + 12 + 9;  //保证最小字节长
    d = (date *)malloc(size);
    d->id = 2016;
    d->age = 18;
    memcpy(d->name,"hongqiang\0",10);
    int name_size = sizeof(d->name);
    int *a = NULL;
    a = (int *)d+2*sizeof(int)+name_size;
    *a = 100;
    cout<<"id:"<<d->id<<endl;
    cout<<"age:"<<d->age<<endl;
    cout<<"name:"<<d->name<<endl;
    cout<<"grade:"<<*a<<endl;


   // cout<<"-------------------十六进制显示---------------"<<endl;
   // char buff[128+12+9] = {0};
   // memcpy(buff,d,size);
   // HexPrint(buff,size);


    return 0;
}
posted @ 2021-05-21 09:39  h云淡风轻  阅读(6)  评论(0编辑  收藏  举报  来源