整数と配列を持つCの構造体がある場合、整数を0に初期化し、配列の最初の要素を0に初期化するには、構造体が別の構造体のメンバーである場合、他の構造体のすべてのインスタンスに対して整数と配列にはそれらの初期化された値がありますか?
5 に答える
7
イニシャライザーは、ネストされた構造体に対してネストできます。
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
于 2012-10-03T06:45:34.900 に答える
3
このサンプルプログラムがお役に立てば幸いです。
#include <stdio.h>
typedef struct
{
int a;
int b[10];
}xx;
typedef struct
{
xx x1;
char b;
}yy;
int main()
{
yy zz = {{0, {1,2,3}}, 'A'};
printf("\n %d %d %d %c\n", zz.x1.a, zz.x1.b[0], zz.x1.b[1], zz.b);
return 0;
}
yy zz = {{0, {0}}, 'A'};
配列b[10]のすべての要素を初期化します。0に設定されます。
@unwindの提案と同様に、Cでは、作成されたすべてのインスタンスを手動で初期化する必要があります。ここにはコンストラクターのようなメカニズムはありません。
于 2012-10-03T07:10:51.650 に答える
1
構造体全体を{0}で0から初期化できます。
例えば:
typedef struct {
char myStr[5];
} Foo;
typedef struct {
Foo f;
} Bar;
Bar b = {0}; // this line initializes all members of b to 0, including all characters in myStr.
于 2012-10-03T06:12:11.537 に答える
1
Cにはコンストラクターがないため、すべての場合に初期化式を使用している場合を除きます。つまり、次のように記述します。
my_big_struct = { { 0, 0 } };
内部構造を初期化するには、関数を追加し、構造が「インスタンス化」されているすべての場合に呼び出されることを確認する必要があります。
my_big_struct a;
init_inner_struct(&a.inner_struct);
于 2012-10-03T06:59:24.877 に答える
1
これは、オブジェクト指向設計でこのようなことを行う方法の代替例です。この例ではランタイム初期化を使用していることに注意してください。
mystruct.h
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
typedef struct mystruct_t mystruct_t; // "opaque" type
const mystruct_t* mystruct_construct (void);
void mystruct_print (const mystruct_t* my);
void mystruct_destruct (const mystruct_t* my);
#endif
mystruct.c
#include "mystruct.h"
#include <stdlib.h>
#include <stdio.h>
struct mystruct_t // implementation of opaque type
{
int x; // private variable
int y; // private variable
};
const mystruct_t* mystruct_construct (void)
{
mystruct_t* my = malloc(sizeof(mystruct_t));
if(my == NULL)
{
; // error handling needs to be implemented
}
my->x = 1;
my->y = 2;
return my;
}
void mystruct_print (const mystruct_t* my)
{
printf("%d %d\n", my->x, my->y);
}
void mystruct_destruct (const mystruct_t* my)
{
free( (void*)my );
}
main.c
int main (void)
{
const mystruct_t* x = mystruct_construct();
mystruct_print(x);
mystruct_destruct(x);
return 0;
}
必ずしもmallocを使用する必要はありません。静的に割り当てられたプライベートメモリプールを使用することもできます。
于 2012-10-03T08:26:14.360 に答える