[英]Initializing a Struct of a Struct
如果我在C中有一個具有整數和數組的結構,如果結構是另一個結構的成員,那么如何將整數初始化為0並將數組的第一個元素初始化為0,以便對於其他結構的每個實例整數和數組有那些初始值?
初始化器可以嵌套用於嵌套結構,例如
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
我希望這個示例程序能幫助....
#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中,所有創建的實例都應手動初始化。 這里沒有構造函數的機制。
您可以使用{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.
C沒有構造函數,所以除非你在每種情況下使用初始化表達式,即寫出類似的東西
my_big_struct = { { 0, 0 } };
要初始化內部結構,你將不得不添加一個函數,並確保在結構被“實例化”的所有情況下調用它:
my_big_struct a;
init_inner_struct(&a.inner_struct);
這是一個替代的例子,你將如何使用面向對象的設計做這樣的事情。 請注意,此示例使用運行時初始化。
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,也可以使用私有的,靜態分配的內存池。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.