ENEE150 Discussion 04 Section 0101 Adam Wang
Overview HW2 Pointers
HW 2 Problem 1 Write your own “tests” to test the check functions in project 1 Check_basic_move Check_entry_move Check_bear_off_move Check_die Check_board_bounds You’ll submit 5 programs: test1-driver.c -> test5-driver.c Just print out whatever’s in the out files
What you’re given required_functions.o Test1.out -> test5.out Contains the 5 check functions and print_board() A *.o file is compiled but not linked; you can use it but you won’t be able to see the code Use like you would use a *.c file Test1.out -> test5.out All the output you need to be able to print with the driver programs Copy in your backgammon.h for the function headers and global variables
Test1.out Put 1 white piece on the_board_white[6] You’ll first need to clear the board Go through the_board[] and set everything to 0 Put 1 white piece on the_board_white[6] Print_board Use simple if statements to decide if you should print “VALID_MOVE” or “INVALID_MOVE” Next put 1 red piece on the_board_red[1] Print board again Do same thing over again
Problem 2: run-tests Write a script file to automatically compile & diff all your files This is NOT a *.c file; this is a shell language Should be ~10 lines of commands
Tips to write the script First line must be #!/bin/csh This tells the shell it’s a cshell script The command to print is echo echo “hello world” A “for” loop looks like this: foreach i (1 2 3 4 5 6) ... other commands go here (gcc, diff, a.out, etc.) end
Other tips In a for loop you can use the value of i in your commands test$i-driver.c Replaces “$i” with whatever value i is After you’ve written and saved, you need to change permissions Type “chmod 777 run-tests” to give yourself executable permissions Then you can run the script just by typing run-tests
Pointers Stores a memory address in hex Can also say it’s a “reference” to another variable or value To initialize a pointer: int *p; Right now this memory address points to garbage & - get the memory address of a variable &a * - get the value at the pointer *p Also “dereference” a pointer
Examples int *p; // new pointer p int *q; int a, b, x; a = 5; *p = a; // set the value of p to whatever’s a b = 6; q = &b; // set q to the memory address of b b = 7; // what happens? q = p; // valid x = *p + 5;
Where have we seen pointers already FILE * inFile; inFile = fopen(“data.txt”, “r”); Stores a pointer to a FILE data type Scanf(“%d”, &var); Reads in an integer and stores it into var Why do we need to do this?
swap void swap (int a, int b) { int temp = a; a = b; b = temp; } int a = 5, b = 10; swap (a,b); // Does NOT work; pass by VALUE
Let’s consider this new swap function void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int p, q; p = 5; q = 10; swap (&p, &q); //This works because of pass by REFERENCE