C语言的可变长数组示例

  struct_array.c

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

struct MyData {
    int len;
    char data[10];
} MyData_t;

struct MyData2 {
    int len;
    char data[];
} MyData2_t;

struct stu {
    int age;
    char name[32];
    //char *name;
};

struct data {
    int len;
    //struct MyData d[0];
    struct stu stu[];
} data_t;

int main()
{
    struct MyData d1;
    struct MyData2 *d2;
    struct data *d3 = NULL;

    printf("test struct and array size. \n");
    printf("struct size:%d, no array:%d \n", sizeof(struct MyData), sizeof(struct MyData2));

    d1.len = 14;
    memcpy(d1.data, "123456789", 10);
    printf("d1 size:%d, data:%s\n", d1.len, d1.data);
    printf("==========1. ===========\n");
    
    d2 = (struct Mydata2 *)malloc(sizeof(int) + 10);
    d2->len = sizeof(int) + 10;
    memcpy(d2->data, "abcdefghi", 10);
    printf("d2 size:%d, data:%s\n", d2->len, d2->data);
    free(d2);

    printf("==========2. ===========\n");
    printf("array: %d\n", sizeof(struct data));

    printf("=========3. ============\n");
    d3 = (struct data *)malloc(sizeof(int) + sizeof(struct stu));
    d3->len = sizeof(int) + sizeof(struct stu) + 32;
    d3->stu[0].age = 18;
    //d3->stu[0].name = (char *)malloc(32);
    memcpy(d3->stu[0].name, "dilireba", sizeof(d3->stu[0].name));
    printf("data len:%d, stu age:%d, name:%s\n", d3->len, d3->stu[0].age, d3->stu[0].name);
    //free(d3->stu[0].name);
    free(d3);

    return 0;
}

编译:

gcc  struct_array.c

输出:

test struct and array size.
struct size:16, no array:4
d1 size:14, data:123456789
==========1. ===========
d2 size:14, data:abcdefghi
==========2. ===========
array: 4
=========3. ============
data len:72, stu age:18, name:dilireba

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值