After completing this lab, you should feel comfortable using pointers, structures, and arrays in C, along with some basic number representation.
Copy the contents of ~cs61c/labs/02 to a suitable location in your home directory.
$ mkdir ~/lab $ cp -R ~cs61c/labs/01b/ ~/lab
A student is experimenting with strings and arrays in C and writes the following code:
#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char hello[] = "hello ", world[] = "world!\n", *s; s = strcat(hello,world); printf(s); return 0; }
Answer the following questions in a text file:
When our student runs her code, it fails to give her the expected result (try it!). Why? What's one way to fix this bug?
(note: not all C compilers emit code that crashes. But the Macs in 200SD crash, and the program is not correct. Side note: you won't crash every time you write a bug in C, and sometimes it will do just what you expect; it's kind of like how you don't always get a ticket when you break the speed limit on the freeway, but it's still illegal).
Here's one to help you in your interviews. In cyclic_ll.c
, complete the function has_cycle
to implement the following algorithm for checking if a singly-linked list has a cycle.
Recall that if p is a pointer to a struct, p->member refers to a member variable in the struct, and is equivalent to (*p).member.
After you have correctly implemented has_cycle
, the program you get when
you compile cyclic_ll.c
will tell you that has_cycle agrees with what the
program expected it to output.
Wednesday's class, we discussed number representation. In particular, we discussed two's complement, the ubiquitous format for signed integers. Look at biggestInt.c. You may wish to read through the comments but at this point it is not critical that you understand exactly how the program works. Basically, it is a C program that will tell you some useful information about certain C data types. It does this by exploiting the fact that C does not check for overflow and wrap around conditions. Compile and run the program and answer the following questions: