I dork this up just about every time I jump back into a C project. I'm getting a segfault when attempting to access a structure within a structure. Let's say I have the following (simplified) structures for a game:
struct vector {
float x;
float y;
};
struct ship {
struct vector *position;
};
struct game {
struct ship *ship;
} game;
And a function to initialize the ship:
static void
create_ship(struct ship *ship)
{
ship = malloc(sizeof(struct ship));
ship->position = malloc(sizeof(struct vector));
ship->position->x = 10.0;
}
Then down in main():
int main() {
create_ship(game.ship);
printf("%f\n", game.ship->position->x); // <-- SEGFAULT
}
typedef struct {float x; float y;} vector;so you don't have to saystructeach time you use the type.