Memory and structs

malloc and free, and grouping data with struct.

C
#include <stdio.h>
#include <stdlib.h>

struct Student {
  int id;
  double cgpa;
};

int main(void) {
  struct Student s = {101, 8.4};
  printf("%d %.1f\n", s.id, s.cgpa);

  int n = 3;
  int *a = malloc(n * sizeof(int));
  if (a == NULL) {
    return 1;
  }
  for (int i = 0; i < n; i++) {
    a[i] = i * 10;
  }
  printf("%d\n", a[2]);
  free(a);
  return 0;
}
Output
101 8.4
20
  • Every malloc needs exactly one free, or the program leaks memory.
  • Check that malloc did not return NULL.
  • Never use memory after freeing it.

Through a pointer to a struct, use the arrow: ptr->id means the same as (*ptr).id.

โ† PointersC quick reference โ†’