In the main function: 1) write code to declare a static array named static_array with a fixed size of 5 integers; 2) write code to dynamically allocate an array named dynamic_array that will be used to store 5 integers; 3) initialize the values in both arrays to be the values 1 through 5; 4) print the middle value of each array.
Answer.
A sample implementation is shown below:
int static_array[5];
int *dynamic_array;
int i;
// allocate heap space for dynamic_array
dynamic_array = (int *) malloc(sizeof(int) * 5);
// Initialize arrays with values 1 to 5
for (i = 0; i < 5; i++) {
static_array[i] = i + 1;
dynamic_array[i] = i + 1;
}
printf("%d\n", static_array[2]);
printf("%d\n", dynamic_array[2]);
Exercise2.4.5.Dynamic Memory Allocation.
Given the following partial program, which of the calls to do_something from main are valid based on do_something’s prototype? Select all that apply.
#include <stdlib.h>
void do_something(int *array, int size);
int main(void) {
int arr1[10];
int *arr2;
arr2 = malloc(sizeof(int)*10);
// assume some initialization code is here
// call do_something here
return 0;
}
do_something(arr1, 10);
Correct!
do_something(arr2, 10);
Correct!
do_something(&arr1, 10);
Incorrect.
do_something(&arr2, 10);
Incorrect.
Exercise2.4.6.Passing Dynamic Arrays to Functions.
#include <stdio.h>
#include <stdlib.h>
void foo(int *b, int c, int *arr, int n) ;
void blah(int *r, int s);
int main(void) {
int x, y, *arr;
arr = (int *)malloc(sizeof(int)*5);
if (arr == NULL) {
exit(1); // should print out nice error msg first
}
x = 10;
y = 20;
printf("x = %d y = %d\n", x, y);
foo(&x, y, arr, 5);
printf("x = %d y = %d arr[0] = %d arr[3] = %d\n",
x, y, arr[0],arr[3]);
free(arr);
return 0;
}
void foo(int *b, int c, int *arr, int n) {
int i;
c = 2;
for (i=0; i<n; i++) {
arr[i] = i + c;
}
*arr = 13;
blah(b, c);
}
void blah(int *r, int s) {
*r = 3;
s = 4;
// DRAW STACK HERE
}
(a)
Step through the execution of this program. What is its output?
Answer.
The program’s output is:
x = 10 y = 20
x = 3 y = 20 arr[0] = 13 arr[3] = 5
(b)
List the values of the array’s elements after the call to foo returns.
Answer.
The array contents are:
13, 3, 4, 5, 6
(c)
Draw the contents of the stack and the heap at the point of execution immediately before the blah function returns.
Answer.
Here is the execution stack drawn at the point shown in function blah: