如果我有一个C中有一个整数和一个数组的结构体,我该如何初始化整数为0,并将数组的第一个元素初始化为0,如果结构体是另一个结构体的成员所以对于其他结构的每个实例,整数和数组都有这些初始化值?初始化结构的struct
回答
Initialisers可以嵌套嵌套结构,例如
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 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.
有没有办法在Bar里面初始化Foo? –
您的意思是b.f = {0}或b.f = someOtherF?否则,C中没有构造函数,因此您无法实现f的默认初始化。 – yuklai
C没有构造,所以,除非您使用的是初始化表达式在任何情况下,即喜欢写东西
my_big_struct = { { 0, 0 } };
初始化内部结构,你将不得不增加一个功能,并确保它被称为在所有情况下的结构“实例”:
my_big_struct a;
init_inner_struct(&a.inner_struct);
用“不透明类型”(aka不完整类型)做到这一点更安全,更优雅。然后调用者将无法访问结构的私有成员变量。 – Lundin
我希望这个示例程序可以帮助....
#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创建的所有实例应该手动初始化。这里没有构造器类型的机制。
这是一个替代的例子,你将如何使用面向对象的设计来做这样的事情。请注意,此示例使用运行时初始化。
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,你可以使用一个私人的,静态分配内存池。
- 1. 初始化struct
- 2. 结构初始化
- 3. 初始化结构
- 4. 初始化结构
- 5. 结构,初始化
- 6. 初始化结构
- 7. 初始化结构
- 8. 初始化结构体中的一个向量struct
- 9. struct的部分初始化?
- 10. 结构的初始化
- 11. 初始化其他结构的结构
- 12. 如何在结构中初始化一个struct数组?
- 13. C++结构体初始值初始化
- 14. 如何初始化struct in6_addr?
- 15. 初始化结构和嵌套结构
- 16. 结构初始化为0
- 17. 初始化数据结构
- 18. C++ const结构初始化
- 19. 结构初始化++错误
- 20. 初始化静态结构
- 21. 初始化C++结构
- 22. 初始化结构指针
- 23. Golang结构初始化
- 24. 结构初始化问题?
- 25. 结构成员初始化
- 26. C++结构初始化
- 27. 初始化结构对象++
- 28. 初始化在C结构
- 29. 结构数组初始化
- 30. 结构成员初始化
代码示例说明你的问题会更好... –
好读:[C和C++:自动结构的部分初始化](http://stackoverflow.com/questions/10828294/c-and-c-partial-初始化自动结构) –