Pointer Types and Arrays
Referencing and dereferencing
Examine the following example and predict its output. Also visualize on a memory band what gets done after each initialization or assignment:
#include <stdio.h> int main() { double x = 1.23; double y = 2.13; double *p = &x; double **q = &p; printf("x = %10.4lf\ny = %10.4lf\n\n", x, y); *p = 6.66; printf("x = %10.4lf\ny = %10.4lf\n\n", x, y); **q = 4.2; printf("x = %10.4lf\ny = %10.4lf\n\n", x, y); *q = &y; *p = 6.66; printf("x = %10.4lf\ny = %10.4lf\n\n", x, y); **q = 4.2; printf("x = %10.4lf\ny = %10.4lf\n\n", x, y); }
Arrays
Complete the following code snippet such that:
-
function init initializes an array of length \(n\) with values \(1, \dots, n\).
-
function sum returns the sume of the elements.
Use the * and bracket notation for accessing elements.
#include <stddef.h> #include <stdio.h> #define N 6 double some_array[N]; void init(size_t n, double *x) { // your code } double sum(size_t n, const double *x) { double res = 0; // your code return res; } int main() { init(N, some_array); printf("res = %10.3lf\n", sum(N, some_array)); return 0; }