teaching machines

CS 330 Lecture 12 – Arrays and malloc

February 17, 2012 by . Filed under cs330, lectures, spring 2012.

Agenda

Code

makefile

EXES = first arrays months

all: $(EXES)

$(EXES): %: %.c
	gcc -o $@ -Wall -std=c99 $<

clean:
	rm -f $(EXES)

arrays.c

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

int average(int nums[], int len) {
  int sum = 0;
  for (int i = 0; i < len; ++i) {
    sum += nums[i];
  }
  return sum / len;
}

int main(int argc, char **argv) {
  int nums[] = {
    10, 15, 30, 10, 15, 30
  };
  printf("average(nums, 6): %d\n", average(nums, 6));

  printf("nums[<0-2>]: %d %d %d %d %d\n",
         nums[0], nums[1], nums[2], nums[3], nums[4]);


  printf("%d\n", 3[nums]);

  return 0;
}

months.c

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

int *get_days_in_months() {
  int *dims = (int *) malloc(sizeof(int) * 12);

  dims[0] = 31;
  dims[1] = 28;
  dims[2] = 31;
  dims[3] = 30;
  dims[4] = 31;
  dims[5] = 30;
  dims[6] = 31;
  dims[7] = 31;
  dims[8] = 30;
  dims[9] = 31;
  dims[10] = 30;
  dims[11] = 31;

  /* { */
    /* 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 */
  /* }; */
  return dims;
}

void foobag() {
  int a = rand();
  int b = rand();
  int c = rand();
  int d = rand();
}

int main(int argc, char **argv) {
  int *arr = get_days_in_months();
  foobag();
  printf("arr[<0-11>]: %d %d %d %d %d %d %d %d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9], arr[10], arr[11]);
  free(arr);
  printf("arr[<0-11>]: %d %d %d %d %d %d %d %d %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9], arr[10], arr[11]);
  return 0;
}

Haiku

Boy scouts are prepared.
“Cool rock. But my pockets! Full!
I’ll malloc new ones.”