【问题标题】:Can you create an array of Structure inside of another structure in C language?你能在 C 语言的另一个结构中创建一个结构数组吗?
【发布时间】:2021-08-05 01:30:33
【问题描述】:

目标:创建具有某些属性的元素结构。然后通过在另一个结构中创建它的数组来利用该结构类型。

struct Element
{
    int i;
    int j;
    int x;
};

struct Sparse
{
    int r;
    int c;
    int n;
    struct Element *ele;
    ele = (struct Element *)malloc(n*sizeof(struct Element));    
}; 

我想知道的是,在创建结构时,我不允许编写代码的哪一部分。

【问题讨论】:

  • ele = (struct Element *)malloc(n*sizeof(struct Element)); 需要在函数中。
  • 您是否尝试编译代码?这会很快告诉你它是无效的。 C 结构定义中不允许使用表达式。

标签: arrays c struct


【解决方案1】:

常见的做法是:

struct Element
{
    int i;
    int j;
    int x;
};

struct Sparse
{
    int r;
    int c;
    int n;
    struct Element ele[0];  // Make a zero length array
}; 

struct Sparse* MakeNewSparse(size_t num_ele)
{
    struct Sparse* sparse = malloc(sizeof(*sparse) + num_ele*sizeof(struct Element));
    return sparse;
}

这是可行的,因为在 C 语言中访问零长度数组的末尾是完全合法的,如果你已经在那里分配了内存。

在这个例子中,我们为struct Sparse分配了足够的空间,然后为struct Element的数组分配了足够多的连续空间。

之后,访问元素sparse->ele[5] 是完全合法的。

【讨论】:

  • 零长度数组是 GCC 扩展。在 C99 中,省略 0:struct Element ele[];
【解决方案2】:

线

ele = (struct Element *)malloc(n*sizeof(struct Element));   

不应该是结构定义的一部分 - 这是你在运行时做的事情,沿着这些思路:

struct Sparse s; // create new struct Sparse instance

s.n = get_some_size();
s.ele = malloc( s.n * sizeof *s.ele );  // no need for cast

【讨论】:

    【解决方案3】:

    c 中的struct 在语法上与intchar 等类型相似。struct 的定义是为了让编译器知道如何使用用struct 声明的变量,例如@987654326 @。所以struct 的定义实际上并不是代码本身。它将在编译时使用。

    但是,malloc() 是一个函数,会在运行时使用,所以将malloc() 放在你的struct 定义中是无稽之谈。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2011-11-06
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多