C中结构成员(指针与数组)的内存分配之间的差异

hen*_*son 1 c memory struct pointers allocation

这两种分配内存的方式有什么有效的区别吗?

1.

typedef struct {
  uint8_t *buffer;
} Container;

Container* init() {
  Container* container = calloc(sizeof(Container), 1);
  container->buffer = calloc(4, 1);
  return container;
}
Run Code Online (Sandbox Code Playgroud)

2.

typedef struct {
  uint8_t buffer[4];
} Container;

Container* init() {
  Container* container = calloc(sizeof(Container), 1);
  return container;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,整个Container结构将被堆分配并buffer指向相同的。这样对吗?

Vla*_*ans 7

它们是有区别的。

我将尝试说明示例。

正如其他人指出的那样:

  1. 第一个示例更难管理,但您可以随时更改缓冲区的大小。
  2. 第二个示例更易于管理(您不必关心单独释放缓冲区),但您只能拥有固定大小的缓冲区。

正如评论中指出的那样:如果缓冲区是结构中的最后一个元素(如提供的示例中所示),则可以为缓冲区分配任何长度。

例如

int extra_bytes_needed = ...;
Container* container = calloc(sizeof(Container) + extra_bytes_needed, 1);
Run Code Online (Sandbox Code Playgroud)

在图像的左侧 - 您的第一个案例。

在图像的右侧 - 您的第二个案例。

左边是第一种情况,右边是第二种情况。