3
typedef struct all{
  int x;
  int ast[5];
}ALL;

ALL x[5];

int main(void){
  ALL y[5];
  // ...
}

我将如何设置一个常量值,ast[5]以便所有数组变量都具有相同的值ast[]

4

2 回答 2

1
typedef struct all {
  int x;
  int ast[5];
} ALL;

ALL x[5];
ALL constast = {0, {1, 2, 3, 4, 5}};

int main(void) {
  ALL y[5] = {[0] = constast, [1] = constast, [2] = constast,
              [3] = constast, [4] = constast};
  // ...
}
于 2013-01-06T16:17:36.013 回答
0

我从标签中假设问题是针对 C 而不是 C++。

您可以有一个函数来获取结构数组的大小并返回指向数组开头的指针,如下所示:

typedef struct my_struct{
    int i;
    int var[5];
} my_struct;

my_struct* init_my_struct(int size){
    my_struct *ptr = malloc(size * sizeof(struct));
    for(my_struct *i = ptr; (i - ptr) < size; i++)
        i->var = // whatever value you want to assign to it
            // or copy a static value to the the array element
}

现在您可以通过这种方式在代码中使用它:

my_struct *my_struct_ptr = init_my_struct(5); // values inited as required

这种方法的缺点是您正在从声明数组转向使用堆上的内存。
此外,您不能阻止某人创建特定大小的数组并以您想要的方式使用它并为其分配值。

于 2013-01-06T16:35:13.787 回答