teaching machines

CS 330 Lecture 11 – Call by *, Addresses, Malloc

February 14, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

TODO

Code

bookmarks.c

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

struct bookmark_t {
  char title[256];
  char url[256];
};

void print(struct bookmark_t *mark);

int main(int argc, char **argv) {

  struct bookmark_t bookmark = {"Reddit", "http://www.reddit.com"};
  print(&bookmark);
  printf("bookmark.title: %s\n", bookmark.title);

  /* bookmark.title = */

  return 0;
}

void print(struct bookmark_t *mark) {
  strcpy(mark->title, "ALL UR BASE R BELONG TO US");
  printf("<a href=\"%s\">%s</a>\n", mark->url, mark->title); 
}

math_stuff.c

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

void divrem(int numerator,
            int denominator,
            int *quotient, 
            int *remainder);

int main(int argc, char **argv) {
  int quotient;
  int remainder;

  divrem(12, 0, "ient, &remainder); 
  printf("quotient: %d\n", quotient);
  printf("remainder: %d\n", remainder);

  return 0;
}

void divrem(int numerator,
            int denominator,
            int *quotient, 
            int *remainder) {
  *quotient = numerator / denominator;
  *remainder = numerator % denominator;
}

weakly_typed.c

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

int main(int argc, char **argv) {

  float n = 17.0f;
  int *address = (int *) &n;
  *address = 3984753;

  printf("n: %e\n", n);

  return 0;
}

path.c

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

char *make_path(char dir[], char file[]) {
  char *path = (char *) malloc(sizeof(char) * 256);

  strcpy(path, dir);
  strcat(path, "/");
  strcat(path, file);

  return path;
}

int main(int argc, char **argv) {
  char dir[] = "/home/johnch";
  char file[] = "days_of_our_lives.mp4";

  char *path = make_path(dir, file);

  printf("path: %s\n", path);
  free(path);
  path = NULL;
  /* printf("path: %s\n", path); */

  return 0;
}

Why?

Haiku

Friend’s son will mow lawns.
Mailman wouldn’t send him mine.
Gave address instead.