====== Arrays [TOC] ====== We next focus on two things: - functions that operate on arrays and - dynamic memory allocation. We also start to use header files instead of forward declaring external functions. We consider :import: session08/array1.c Exercise ======== The above code does not use any functions. Extend the following code snippet for this purpose. Make meaningful declarations for function parameters (i.e. use `const` were appropriate): ---- CODE(type=c) -------------------------------------------------------------- int printf(const char *, ...); /* your code here */ int main() { int x[5]; // init x init_array(5, x); // print x print_array(5, x); // sum elements of x int sum = sum_array(5, x); printf("sum = %d\n", sum); } -------------------------------------------------------------------------------- Exercise ======== The array in the previous example is stored on the stack as it is defined locally. However, that requires that the array size is rather small. For some reason we do not want to define it as global variable (such that it would be stored in the data segment). Hence, we want to allocate memory dynamically. Extend the code snippet: ---- CODE(type=c) -------------------------------------------------------------- //int //printf(const char *, ...); #include //void * //malloc(size_t size); // //void //free(void *ptr); #include /* your code here */ int main() { unsigned int n = 5; /* your code here */ // init x init_array(n, x); // print x print_array(n, x); // sum elements of x int sum = sum_array(n, x); printf("sum = %d\n", sum); /* your code here */ } --------------------------------------------------------------------------------