Allocate and Release Records
Allocate two inventory records
An inventory can allocate records just as it allocates integer counts. Here n is two, and malloc(n * sizeof *items) requests enough space for two struct Count objects. Check the result before using either record, initialize their fields, and release the space once after printing. If n came from untrusted input, you would also need to ensure the multiplication cannot overflow; this example uses a fixed small count.
You have already used a structure to group fields. The allocation step changes where the records live, not how you access their fields: items[0] selects the first record, and .units selects its member. sizeof *items measures a whole struct Count, including any padding the implementation needs.
Here main owns one allocation containing both records. One free(items) releases the entire block; you must not free each array element separately. If a helper returned this allocated array instead, the caller would need both its address and its element count, plus a clear agreement about who calls free.
#include <stdio.h>
#include <stdlib.h>
struct Count {
int units;
};
int main(void) {
size_t n = 2;
struct Count *items = malloc(n * sizeof *items);
if (items == NULL) {
return 1;
}
items[0].units = 2;
items[1].units = 3;
printf("Units: %d\n", items[0].units + items[1].units);
free(items);
return 0;
}
The two records hold 2 and 3 units, so the print shows Units: 5. Notice that the NULL check comes before both indexed writes and free comes after the final read.