在结构体中如何使用动态数组?

294 天前
 icemanpro
struct a1{
int a;
int b;
};

struct bb{
a1 list[];
}

像这样在结构体 bb 中定义了 a1 类型的动态数组。

应该如何使用 bb 这个结构体?有没有代码

1679 次点击
所在节点    C++
16 条回复
liyang5945
294 天前
需要知道 a1 的 length ,不然没法搞
codehz
294 天前
c 里有 flexible array member ( https://en.cppreference.com/w/c/language/struct ),c++里可没有,不建议搞
ArcanusNEO
294 天前
如果不能用 STL 容器的话,可以试试零长度数组这个 gcc 扩展,缺点是 msvc 用不了、会引入很多 C 风格代码、一个结构体里只能存在一个零长度数组
ArcanusNEO
294 天前
@ArcanusNEO stackoverflow 上 flexible array member [相关的讨论]( https://stackoverflow.com/a/67894135)
ysc3839
294 天前
@ArcanusNEO MSVC 好像能用?印象中 Windows SDK 里面就用到了。去搜索了一下,只是会产生 warning 。
thorneLiu
294 天前
土问这个 a1 list[]合法吗
为啥不用 STL?
ArcanusNEO
294 天前
@ysc3839 搜了一下似乎确实可以,不过印象里曾经因为相关的写法编译失败。可能比 gcc 多一些限制,也可能只是我记错了。。。
tyzandhr
294 天前
为什么不用指针?
ArcanusNEO
294 天前
@thorneLiu
在 C 里面合法,C++里不合法;
正常情况下 C++用 STL 应该更合适一点
ysc3839
294 天前
@thorneLiu 有的时候想要扁平可变长的,比如开头一个 size ,后面重复多个元素,用 STL 的话就不能一个指针传递全部数据了。
yolee599
294 天前
放一个指针,然后 malloc [doge]
Perfect1zsh1t
294 天前
```cpp
/*************************************************************************
> File Name: test.c
> Author: JerryChen
> Created Time: 三 7/19 17:27:42 2023
> Description:
************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define N 10 // the length of softarray

typedef struct A1 {
int a;
int b;
}a1;

typedef struct bb {
int len;
a1 list[];
}a1_array;

void init_function(a1_array *t) {
int i = 0;
for(i = 0; i < N; ++i) {
t->list[i].a = i;
t->list[i].b = i << 1;
}
}

void print_array(a1_array *t) {
int i = 0;
for(i = 0; i < N; ++i) {
printf("%d %d\n", t->list[i].a, t->list[i].b);
}
}

int main() {
a1_array *t = (a1_array *)malloc(sizeof(a1_array) + sizeof(*(t->list)) * N);
memset(t, 0, sizeof(*(t->list)));
t->len = N;

init_function(t); // 初始化 list

print_array(t);

return 0;
}

```
cnbatch
294 天前
struct bb { a1 list[1]; };

然后

std::unique_ptr<int64_t[]> ptr = std::make_unique<int64_t[]>(100);

bb *bb_ptr = (bb*)ptr.get();
bb_ptr->list[50].a = 100;
cnbatch
294 天前
如果不介意引入第三方 header ,那么可以试试这个:
https://github.com/cnbatch/dynarray
我在两年前做的动态数组库
bfjm
293 天前
柔性数组吧
changz
293 天前
看看 php 内核的字符串怎么实现的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/957998

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX