c——动态数组

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

typedef struct test_s test_t;

struct test_s {
    int a;
    int b;
    char arr[0];
};

int main()
{
    test_t *t;
    char buf[32] = {0};
    int i;

    t = (test_t *)buf;
    t->a = 1;
    t->b = 2;
    memcpy(t->arr, "123", 3);

    printf("%d, %d, %s\n", sizeof(test_t), t->a, t->arr);

    for (i = 0; i < sizeof(buf); i++) {
        printf("%x ", buf[i]);
    }
    printf("\n");

    return 0;
}

运行结果
8, 1, 123
1 0 0 0 2 0 0 0 31 32 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
如果做下调整

struct test_s {
    int a;
    char arr[0];
    int b;
};

则会导致覆盖
1 0 0 0 31 32 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
说明 char arr[0],没有静态分配内存,只是定义一个符号给编译器用,符号表示的地址为 char arr[0] 前声明的分配了内存的空间的偏移。

这样的好处:避免指针的复杂操作,比如上面代码用指针只能:

typedef struct test_s test_t;

struct test_s {
    int a;
    int b;
    char *arr;
};

int main()
{
    test_t *t;
    char buf[32] = {0};
    int i;

    t = (test_t *)buf;
    t->a = 1;
    t->b = 2;
    t->arr = (char *)t + sizeof(*t);
    memcpy(t->arr, "123", 3);

    printf("%d, %d, %s\n", sizeof(test_t), t->a, t->arr);

    for (i = 0; i < sizeof(buf); i++) {
        printf("%x ", buf[i]);
    }
    printf("\n");

    return 0;
}

运行结果

12, 1, 123
1 0 0 0 2 0 0 0 ffffffa8 69 ffffffcb ffffffbf 31 32 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

posted on   开心种树  阅读(28)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示