Si tengo una estructura en C que tiene un entero y una matriz, ¿cómo puedo inicializar el entero a 0 y el primer elemento de la matriz a 0, si la estructura es un miembro a otra estructura de manera que para cada instancia de la otra estructura? ¿El entero y la matriz tienen esos valores inicializados?
Los inicializadores se pueden anidar para estructuras anidadas, por ejemplo,
typedef struct { int j; } Foo; typedef struct { int i; Foo f; } Bar; Bar b = { 0, { 0 } };
Espero que este progtwig de ejemplo ayude …
#include 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'};
se inicializarán todos los elementos de la matriz b [10] se establecerá en 0.
Al igual que la sugerencia de @unwind, en C todas las instancias creadas deben inicializarse manualmente. No hay ningún tipo de mecanismo de construcción aquí.
Puede 0-inicializar toda la estructura con {0}.
Por ejemplo:
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 no tiene constructores, por lo tanto, a menos que esté utilizando una expresión de inicialización en todos los casos, es decir, escriba algo como
my_big_struct = { { 0, 0 } };
Para inicializar la estructura interna, tendrá que agregar una función y asegurarse de que se llame en todos los casos en que la estructura esté “instanciada”:
my_big_struct a; init_inner_struct(&a.inner_struct);
Aquí hay un ejemplo alternativo de cómo haría las cosas así con un diseño orientado a objetos. Tenga en cuenta que este ejemplo utiliza la inicialización en tiempo de ejecución.
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 #include 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 ); }
C Principal
int main (void) { const mystruct_t* x = mystruct_construct(); mystruct_print(x); mystruct_destruct(x); return 0; }
No necesariamente tiene que usar malloc, también puede usar un conjunto de memoria privado, asignado estáticamente.