CS430 Lab 3: Practice with C Memory Addresses

Due Thursday, September 14

Here are a couple puzzles that may provide amusement, plus test your understanding of pointers in C. These will also be similar to a midterm question, so I would recommend reviewing this lab shortly before the midterm.

1. What is the output of this program?


void foo(int (*bar)(int*)){
	int a = 2;
	printf("%d\n", bar(&a));
	printf("%d\n", a);

int main() {
	int a = 5;
	int b = 10;
	int bar(int* a){
		b = b - *a;
		*a = *a - *a;
		return *a + b;
	printf("%d\n", a);
	printf("%d\n", b);
	return 0;
You can check your answer easily enough with a compiler, but try to solve it normally first.

2. Structure Pointers

Consider this function:
void call_actions(struct actions* a){
		printf("We can walk!  Now we try running!\n");
	} else {
		printf("No walking is possible without dinner.\n");
call_actions expects a structure with three functions. Walk returns a 0 if walking is not possible, and instead eat_dinner is called. If walking is possible, then run is called. Create three functions, walk, run, and eat_dinner, package them in a struct, and write a main function that calls call_actions. The functions can do anything you want them to.
If you have already done project 1, then this part of the lab should be very easy. If not, this will serve as a warm-up exercise for project 1.