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指向相同的。这样对吗?
它们是有区别的。
我将尝试说明示例。
正如其他人指出的那样:
正如评论中指出的那样:如果缓冲区是结构中的最后一个元素(如提供的示例中所示),则可以为缓冲区分配任何长度。
例如
int extra_bytes_needed = ...;
Container* container = calloc(sizeof(Container) + extra_bytes_needed, 1);
Run Code Online (Sandbox Code Playgroud)
在图像的左侧 - 您的第一个案例。
在图像的右侧 - 您的第二个案例。