如果我在C中有一个包含整数和数组的结构,如何将整数初始化为0并将数组的第一个元素初始化为0,如果结构是另一个结构的成员,那么对于每个实例都是另一个结构是整数,数组是否有那些初始值?
答案 0 :(得分:6)
初始化者可以嵌套嵌套结构,例如
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
答案 1 :(得分: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中,所有创建的实例都应手动初始化。这里没有构造函数的机制。
答案 2 :(得分:1)
您可以使用{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.
答案 3 :(得分:1)
C没有构造函数,所以除非你在每种情况下都使用初始化表达式,比如写
my_big_struct = { { 0, 0 } };
初始化内部结构,你将不得不添加一个函数,并确保在结构被“实例化”的所有情况下调用它:
my_big_struct a;
init_inner_struct(&a.inner_struct);
答案 4 :(得分: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,也可以使用私有的,静态分配的内存池。