In dynamically allocating memory for a struct, I ran across some code that does
struct simulation *sim_one = calloc(1, sizeof(*sim_one));
Is there any reason to prefer using calloc
over malloc
for structs? In this context, do they do the same thing? Also, I've only ever seen sizeof
called with a datatype; however, the calloc
example calls sizeof
on a pointer to a variable sim_one
which, I would think, doesn't exist at the moment when sizeof
is called, but compilation and execution leads to no errors. See below for the malloc
example.
struct simulation *sim_two = malloc(sizeof(struct simulation));
The latter option is syntax for which I am familiar from allocations such as double *var = malloc(sizeof(double))
.
I define the structs here for clarity:
struct particle {
double x;
double y;
double z;
};
struct simulation {
struct particle particles[100];
};
int main(){
struct simulation *sim_one = calloc(1, sizeof(*sim_one)); // why?
struct simulation *sim_two = malloc(sizeof(struct simulation)); // familiar malloc syntax
}