WeCodeAcademy

C Memory and structs

A struct groups related values. malloc asks for memory at run time and free gives it back. Always free what you allocate.

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

struct Point {
  int x;
  int y;
};

int main(void) {
  struct Point p = {3, 4};
  printf("(%d, %d)\n", p.x, p.y);

  struct Point *pp = &p;
  printf("%d\n", pp->x + pp->y);

  int *nums = malloc(3 * sizeof(int));
  for (int i = 0; i < 3; i++) nums[i] = (i + 1) * 10;
  printf("%d %d %d\n", nums[0], nums[1], nums[2]);
  free(nums);
  return 0;
}
Output
(3, 4)
7
10 20 30
Quick check

What must you do with memory from malloc?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.