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 2022-11-17 13:17  开心种树  阅读(23)  评论(0编辑  收藏  举报