estructuras anidadas y punteros
Trato esto casi cada vez que vuelvo a un proyecto en C. Obtengo un error de seguridad al intentar acceder a una estructura dentro de una estructura. Digamos que tengo las siguientes estructuras (simplificadas) para un juego:
struct vector {
float x;
float y;
};
struct ship {
struct vector *position;
};
struct game {
struct ship *ship;
} game;
Y una función para inicializar el barco:
static void
create_ship(struct ship *ship)
{
ship = malloc(sizeof(struct ship));
ship->position = malloc(sizeof(struct vector));
ship->position->x = 10.0;
}
Luego abajo en main ():
int main() {
create_ship(game.ship);
printf("%f\n", game.ship->position->x); // <-- SEGFAULT
}