[英]Array of Structs within the same Struct in C
有什么方法可以在C中创建结构并创建具有相同类型结构的数组?
例如
typedef struct Vertex{
char letter;
Vertex edges[];
}Vertex;
我需要在同一结构中包含一系列结构。 在C中这有可能吗?
您可以执行以下操作:
typedef struct _Vertex {
char letter;
struct _Vertex* pEdges;
} Vertex;
Vertix v;
v.pEdges = (Vertex*)malloc(sizeof(Vertex) * n);
v.pEdges[0].letter = '0';
您需要某种方式来知道/跟踪每个数组中有多少个项目。
让我们假设一下,根据对不同答案的评论 ,我知道您真正要寻找的是:一种将有限数量的Vertex结构引用为某个顶点的边的方法,并且必须为所有顶点记录复制该方法在你的有限集中
假设它是顶点结构的线性列表; 一个指定大小的已分配数组,(或通过realloc()
算法不断扩展):
-----------------------------------------
| Vertex[0] | Vertex[1] | Vertex[2] ... |
-----------------------------------------
现在,假设上述各项的末尾都需要某种方式来协调
Vertex Edges
------ -------
[0] [1],[2]
[1] [0],[2]
[2] [0],[1]
很抱歉使用一个简单的三角形,但这是我能想到的最简单的例子。 无论如何继续前进。 如果这是您要寻找的模型,则可以如下定义顶点结构:
typedef struct Vertex
{
char value; // node 'value'
int n; // number of edge indices.
int *edges; // dynamic edge index list. [0..(n-1)]
} Vertex;
在定义上面的示例时,您将执行以下操作。
一个简单(非常)的例子是必要的:
Vertex vtx[3];
// wire vtx[1] and vtx[2] as edges of vtx[0].
vtx[0].value = 'a';
vtx[0].n = 2;
vtx[0].edges = malloc(2 * sizeof(int));
vtx[0].edges[0] = 1;
vtx[0].edges[1] = 2;
// wire vtx[0] and vtx[2] as edges of vtx[1].
vtx[1].value = 'b';
vtx[1].n = 2;
vtx[1].edges = malloc(2 * sizeof(int));
vtx[1].edges[0] = 0;
vtx[1].edges[1] = 2;
// wire vtx[0] and vtx[1] as edges of vtx[2].
vtx[2].value = 'c';
vtx[2].n = 2;
vtx[2].edges = malloc(2 * sizeof(int));
vtx[2].edges[0] = 0;
vtx[2].edges[1] = 1;
因此,假设您有vtx [0]。 您如何到达他的第一个优势?
Vertex *edge = vtx[ vtx[0].edges[0] ];
从那里您可以移至该边缘的第一边缘
edge = vtx[ edge->edges[0] ];
等等。一张图片值一千个字:
-------------------------------------
| Vertex[0] | Vertex[1] | Vertex[2] |
| value = a | value = b | value = c |
| count = 2 | count = 2 | count = 2 |
|-----------|-----------|-----------|
|edges[0]=1 |edges[0]=0 |edges[0]=0 |
|edges[1]=2 |edges[1]=2 |edges[1]=1 |
-------------------------------------
清理需要您在全局列表的每个顶点中使用free()
索引列表指针。 如果全局列表本身是动态分配的,则也可以对其进行free()
。 在上面的示例中,事实并非如此。
我希望至少能使您了解如何执行此操作而不必使用malloc-nutz并在各处复制数据。 总而言之,在此示例中,可以利用“顶点”节点列表来维护您真正想要的信息(边缘),而无需制作任何“顶点”节点的副本。
就像乔纳森·伍德(Jonathan Wood)和ouah所说的那样做。 在C语言中,我们无法将数组(实际上是struct本身)放入struct中。 但是,指向该结构的指针确实可以正常工作。 例如,当我们用C实现一个列表时,我们经常使用以下结构:
struct listname{
void *value;
struct listname *next;
}
然后,为了放置一个数组,将一个指向该结构的数组的指针放入其中。
typedef struct Vertex{
char letter;
struct Vertex *edges;
int n;
}Vertex;
要么
typedef struct Vertex Vertex;
struct Vertex{
char letter;
Vertex *edges;
int n;
};
例如:
Vertex bla;
const int n = 42;
bla.n = n;
bla.edges = malloc(n * sizeof (*bla.edges));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.