← The C Language
Lesson 53 of 77 · 10 XP
Structs and dynamic memory
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Structs are often created on the heap: for example, when their number isn't known in advance, or when an object must live longer than the function that created it.
struct player {
char *name; // the string is on the heap too
int score;
};
struct player *player_new(const char *name)
{
struct player *p = malloc(sizeof *p);
if (p == NULL)
return NULL;
p->name = malloc(strlen(name) + 1);
if (p->name == NULL) {
free(p);
return NULL;
}
strcpy(p->name, name);
p->score = 0;
return p;
}
void player_free(struct player *p)
{
if (p == NULL)
return;
free(p->name); // first what the fields point to
free(p); // then the struct itself
}
A pair of "constructor xxx_new + destructor xxx_free" is the standard style in C libraries. It's a manual version of what constructors and destructors do in C++.
Task. Finish player_new and player_free following the example above. The program creates a player by name, adds points from the input to them and prints name: points.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.