0xLeon

C Struct Initialization Example

Aug 31st, 2015
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.52 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3.  
  4. typedef struct game {
  5.     int enemy_count;
  6.     int bullet_count;
  7. } game_t;
  8. typedef game_t* game_p;
  9.  
  10. void main() {
  11.     game_t stack_game = {
  12.         .enemy_count = 10,
  13.         .bullet_count = 0
  14.     };
  15.    
  16.     game_p heap_game = malloc(sizeof(game_t));
  17.    
  18.     if (NULL == heap_game) {
  19.         // actually should handle the error, display a message and free bound resources before aborting
  20.         abort();
  21.     }
  22.    
  23.     heap_game->enemy_count = 10;
  24.     heap_game->bullet_count = 0;
  25.    
  26.     // do stuff
  27.    
  28.     free(heap_game);
  29. }
Advertisement
Add Comment
Please, Sign In to add comment