typedef struct all{
int x;
int ast[5];
}ALL;
ALL x[5];
int main(void){
ALL y[5];
// ...
}
ast[5]
すべての配列変数が同じ値になるように定数値をに設定するにはどうすればよいast[]
ですか?
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};
// ...
}
タグから、質問は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
このアプローチの欠点は、配列の宣言からヒープ上のメモリの使用に移行していることです。
また、誰かが特定のサイズの配列を作成し、必要な方法で値を割り当てて使用することを防ぐことはできません。