C中相同Struct中的Structs数组

时间:2012-11-17 01:48:50

标签: c arrays struct

有没有办法创建一个结构,并在C中创建一个相同类型结构的数组?

e.g。

typedef struct Vertex{
    char letter;
    Vertex edges[];
}Vertex; 

我需要在同一结构中的一组结构。在C中这有可能吗?

4 个答案:

答案 0 :(得分:3)

你可以这样做:

typedef struct _Vertex {
    char letter;
    struct _Vertex* pEdges;
} Vertex; 

Vertix v;
v.pEdges = (Vertex*)malloc(sizeof(Vertex) * n);
v.pEdges[0].letter = '0';

您需要某种方式来了解/跟踪每个阵列中有多少项目。

答案 1 :(得分:1)

让我们暂时假设我根据您的comment to a different answer了解您真正寻找的内容:一种将有界数量的顶点结构作为某个顶点的边缘参考的方法,这必须复制到有限集中所有顶点记录。

假设它是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;

在定义上述示例时,您将执行以下操作。

  1. 确定全局列表中的哪些顶点条目是当前条目的边缘。
  2. 分配动态索引列表以保留那些边缘'ID'的插槽。
  3. 将每个边缘顶点索引分配到索引列表中。
  4. 一个简单的(非常)例子是有道理的:

    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并复制数据的情况下完成这项工作。总之,在此示例中,可以利用“顶点”节点列表来维护您真正想要的信息(边缘),而无需复制顶点节点。

答案 2 :(得分:1)

就像Jonathan Wood和ouah所说的那样。 在C中,我们不能将数组(实际上是结构本身)放入结构中。但是,指向结构的指针将非常正常。 例如,当我们通过C实现列表时,我们经常使用以下结构:

struct listname{
    void *value;
    struct listname *next;
}

然后,为了放置一个数组,将一个指向结构数组的指针放入其中。

答案 3 :(得分:0)

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));