gpt4 book ai didi

char 指针与 char 数组不同?

转载 作者:IT王子 更新时间:2023-10-29 06:04:40 26 4
gpt4 key购买 nike

阅读source code of Redis :

struct sdshdr {
int len;
int free;
char buf[];
};

我发现 char buf[] 不能替换为 char *buf,因为 char* buf 会增加结构的大小。

但我不明白为什么,有人能解释一下吗?


编辑:我已经在我的 x86_64 Ubuntu(3.2.0-23-generic) 上用 gcc 4.6.3 像这样测试了它:

printf("sdshdr len = %zu\n", sizeof(struct sdshdr));

使用 char buf[] 它输出 sdshdr len = 8sdshdr len = 16 使用 char *buf.

最佳答案

声明buf 成员的方式利用了称为灵活数组 的C99 功能,主要优点是获得use of variable length array like features inside a struct。 .由于 buf 声明时没有指定大小,除非您在动态分配 struct sdshdr * 时显式分配它,否则它不会占用空间。

它比使用 char * 更有效,因为如果 bufchar * 我们必须执行两次动态分配,首先对于 struct sdshdr * 然后对于 bufpointer 本身将需要额外的空间。这更干净,因为分配作为一个单元成功或失败,并且清理更简单,因为只需要一个 free。我们还获得了数据的局部性,因为整个结构是在一个 block 中分配的,不需要单独的取消引用来访问 buf

draft C99 standard6.7.2.1 部分中有一个很好的示例展示了如何使用此功能:

EXAMPLE After the declaration:

struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this
is:

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p
behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

(there are circumstances in which this equivalence is broken; in particular, the
offsets of member d might not be the same).

关于char 指针与 char 数组不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com