Initializing structure structure

If I have a structure in C that has an integer and an array, how to initialize an integer to 0 and the first element of the array to 0, if the structure is a member of another structure, so for each instance a different structure is an integer, and the array has these initialized values?

+3
c
source share
5 answers

Initializers can be nested for nested structures, for example.

typedef struct { int j; } Foo; typedef struct { int i; Foo f; } Bar; Bar b = { 0, { 0 } }; 
+6
source share

I hope this sample program helps ...

 #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'}; will initialize all elements of the array b [10], the value 0 will be set.

Like the @unwind clause, in C, all instantiated instances must be initialized manually. There is no constructor.

+3
source share

You can 0-initialize the entire structure with {0}.

For example:

 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
source share

C has no constructors, so if you do not use an initializer expression in each case, that is, write something like

 my_big_struct = { { 0, 0 } }; 

to initialize the internal structure, you will need to add a function and make sure that it is called in all cases when the structure is "created":

 my_big_struct a; init_inner_struct(&a.inner_struct); 
+1
source share

Here is an alternative example of how you do such things with an object oriented design. Note that this example uses runtime initialization.

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; } 

You don't have to use malloc, you can use a private, statically allocated memory pool.

+1
source share

All Articles