CSC209H Worksheet: Function Calls and Pointers
1. Trace the memory usage for the program below up to the point when lie returns. We have set up both stack frames for you.
#include
void lie(int age) {
printf(“You are %d years old\n”, age);
age += 1;
printf(“You are %d years old\n”, age);
}
int main() {
int age = 18;
lie(age);
printf(“But your age is still %d\n”, age);
return 0;
Section
stack frame for lie
stack frame for main
Address
0x23c
0x240
0x244
0x248
0x24c
0x250
0x254
0x258
0x25c
0x260
0x264
Value Label
age
}
2. In the space below, modify the above program so that lie takes in a pointer so that the change it makes persists after it returns. Trace through your new program (you’ll need to write sections and labels yourself).
Section
Address
0x23c
0x240
0x244
0x248
0x24c
0x250
0x254
0x258
0x25c
0x260
0x264
Value
Label
age
CSC209H Worksheet: Function Calls and Pointers
3. In the space below, write a small program that allocates an array of integers in the main function and passes that array to a function call change. (You’ll also need to pass in the length of the array – why?) The function should do two things:
• Add 10 to each element of the array.
• Return the average of the new contents of the array.
Check your understanding carefully by tracing the execution of the function on the given memory model diagram.
Section
Address
0x23c
0x240
0x244
0x248
0x24c
0x250
0x254
0x258
0x25c
0x260
0x264
0x268
0x26c
Value
Label