C beginner here, so bear with me.
I have a function that does a yahtzee roll:
Code:
#include <stdlib.h>
#define DIE_SIDES 6
#define MAX_DICE_PER_ROLL 5
typedef struct Roll {
int dice[MAX_DICE_PER_ROLL];
int num_dice;
} Roll;
/**
* Roll n dice. If less than 6 die are
* rolled, zeros out the remaining slots.
*/
Roll* roll_dice(int num_dice) {
static Roll roll;
roll.num_dice = num_dice;
for (int i = 0; i < MAX_DICE_PER_ROLL; i++) {
if (i < num_dice) {
// roll_die is declared else where and returns a
// random number between 1-6.
roll.dice[i] = roll_die();
} else {
// Zero out dice that are not rolled.
roll.dice[i] = 0;
}
}
return &roll;
}
A few questions about the code I've written:
1. I am returning a pointer to Roll, as I understand this is best practice instead of returning the actual struct instance. Mostly this is because it allows the struct to add properties and other code that's using this will still compile. In my case it's really a matter of style/convention. True or false?
2. Since I return a reference to the roll, I must either declare the roll static or allocate on the heap so that the reference returned refers to a memory location that is still valid past the enclosing function's execution lifetime. Both declaring this static and dynamically allocating on the heap seem to serve the same purpose here, so what's the difference exactly and what is most appropriate for this function? My guess is that if I have many rolls, static allocation is wasteful because the memory allocated for each roll lives as long as the program does, whereas dynamic allocation of that roll allows me to localize the memory usage and it can be reclaimed by the caller...is that right?
3. Would it be better to have a dynamically allocated array of dice in the struct vs. padding it with zeros to represent n dice out of 5 that weren't rolled?
Thanks for your patience.