2012-10-03 54 views
3

如果我有一个C中有一个整数和一个数组的结构体,我该如何初始化整数为0,并将数组的第一个元素初始化为0,如果结构体是另一个结构体的成员所以对于其他结构的每个实例,整数和数组都有这些初始化值?初始化结构的struct

+4

代码示例说明你的问题会更好... –

+0

好读:[C和C++:自动结构的部分初始化](http://stackoverflow.com/questions/10828294/c-and-c-partial-初始化自动结构) –

回答

6

Initialisers可以嵌套嵌套结构,例如

typedef struct { 
    int j; 
} Foo; 

typedef struct { 
    int i; 
    Foo f; 
} Bar; 

Bar b = { 0, { 0 } }; 
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. 
+1

有没有办法在Bar里面初始化Foo? –

+1

您的意思是b.f = {0}或b.f = someOtherF?否则,C中没有构造函数,因此您无法实现f的默认初始化。 – yuklai

1

C没有构造,所以,除非您使用的是初始化表达式在任何情况下,即喜欢写东西

my_big_struct = { { 0, 0 } }; 

初始化内部结构,你将不得不增加一个功能,并确保它被称为在所有情况下的结构“实例”:

my_big_struct a; 

init_inner_struct(&a.inner_struct); 
+1

用“不透明类型”(aka不完整类型)做到这一点更安全,更优雅。然后调用者将无法访问结构的私有成员变量。 – Lundin

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创建的所有实例应该手动初始化。这里没有构造器类型的机制。

+1

您仍然可以在C中使用构造函数/析构函数,但缺点是您必须显式调用它们,它们不会像使用内置OO支持的语言那样自动调用。以我的答案为例。 – Lundin

+1

@Lundin谢谢。但是mystruct_construct()需要为每个实例调用正确的? – Jeyaram

+0

事实上,每一个例子。 – Lundin

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,你可以使用一个私人的,静态分配内存池。