c语言,变长数组

 

下面这个结构体,可以在malloc的时候指定数据data的长度,这样的形式就是变长数组
typedef struct
{
  int data_len;
  char data[0];//或char data[];
}buff_st_a;


用法:在下面的例子中,
buff_st_b和buff_st_a用法相同,用数组名来表示数据地址,这时数据是紧挨着p_struct的,这样p_struct和p_data不用各自分开分配和释放,使用起来很方便;
buff_st_p用指针来存储数据地址,这时数据的地址并不是紧挨着p_struct的,p_struct和p_data必须各自分开分配和释放;

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

typedef struct
{
    int data_len;
    char data[0];
}buff_st_a;

typedef struct 
{
    int data_len;
    char data[];
}buff_st_b;

typedef struct
{
    int data_len;
    char *data;
}buff_st_p;

typedef struct 
{
    uint32_t id;
    uint32_t age;
}data_st;

void show_data(const data_st *data)
{
    printf("data:\n id :%u,age :%u\n\n", data->id, data->age);
}
void show_addr(char* type, void* p_buf)
{
  printf("for %s,\naddress:\n ", type);
	
  if(0 == strcmp(type, "buff_st_a")){
    buff_st_a *pbuf = (buff_st_a*)p_buf;
    printf("pbuf :%p\t,pbuf->data_len :%p\t,pbuf->data :%p\t\n",
            pbuf, &(pbuf->data_len), pbuf->data);
  }else if(0 == strcmp(type, "buff_st_b")){
    buff_st_b *pbuf = (buff_st_b*)p_buf;
    printf("pbuf :%p\t,pbuf->data_len :%p\t,pbuf->data :%p\t\n",
            pbuf, &(pbuf->data_len), pbuf->data);
  }else if(0 == strcmp(type, "buff_st_p")){
    buff_st_p *pbuf = (buff_st_p*)p_buf;
    printf("pbuf :%p\t,pbuf->data_len :%p\t,pbuf->data :%p\t\n",
            pbuf, &(pbuf->data_len), pbuf->data);
    }
        
}

int useage()
{
    data_st *data = (data_st *)malloc(sizeof(data_st));
    data->id = 100;
    data->age = 23;

    buff_st_a *buffa = (buff_st_a *)malloc(sizeof(buff_st_a) + sizeof(data_st));
    buffa->data_len = sizeof(data_st);
    memcpy(buffa->data, data, buffa->data_len);
	show_addr("buff_st_a", buffa);
    show_data((data_st*)buffa->data);

    buff_st_b *buffb = (buff_st_b *)malloc(sizeof(buff_st_b) + sizeof(data_st));
    buffb->data_len = sizeof(data_st);
    memcpy(buffb->data, data, buffb->data_len);
	show_addr("buff_st_b", buffb);
    show_data((data_st*)buffb->data);
    
    buff_st_p *buffp = (buff_st_p *)malloc(sizeof(buff_st_p));
    buffp->data_len = sizeof(data_st);
    buffp->data = (char *)malloc(buffp->data_len);
    memcpy(buffp->data, data, buffp->data_len);
	show_addr("buff_st_p", buffp);
    show_data((data_st*)buffp->data);

    free(buffa);
    
    free(buffb);
    
    free(buffp->data);
    free(buffp);

    free(data);
    return 0;
}

int main()
{
    useage();
    return 0;
}

  

 

/*
for buff_st_a,
address:
pbuf :0x892f018 ,pbuf->data_len :0x892f018 ,pbuf->data :0x892f01c
data:
id :100,age :23

 

for buff_st_b,
address:
pbuf :0x892f028 ,pbuf->data_len :0x892f028 ,pbuf->data :0x892f02c
data:
id :100,age :23

 

for buff_st_p,
address:
pbuf :0x892f038 ,pbuf->data_len :0x892f038 ,pbuf->data :0x892f048
data:
  id :100,age :23

*/

C语言变长数组data[0]【总结】

 

char data[0]用法总结

你可能感兴趣的:(C语言)