notes/education/software development/ECE1400/Chapter 11 Exercises.md

30 lines
929 B
Markdown
Raw Permalink Normal View History

2024-11-01 19:18:59 +00:00
> 1. If `i` is a variable and `p` points to `i`, which of the following expressions are aliases for `i`?
2024-10-25 19:51:54 +00:00
2024-11-01 19:18:59 +00:00
a. `*p`
g. `*&i`
2024-10-25 20:06:54 +00:00
2024-11-01 19:18:59 +00:00
> 2. If `i` is an `int` variable and `p` and `q` are pointers to `int`, which of the following assignments are legal?
2024-11-01 19:23:59 +00:00
e. `p = *&q;`
f. `p = q;`
i. `*p = *q`
> 3. The following function supposedly computes the sum and average of the numbers in the array `a`, which has length `n`. `avg` and `sum` point to the variables that the function should modify, unfortunately the function contains several errors, find and correct them.
```c
void avg_sum(double a[], int n, double *avg, double *sum)
{
int i;
// This was assigning a pointer to a float,
// the dereference operator was missing
*sum = 0.0;
for (i = 0; i < n; i++)
// This wasn't increasing the value
2024-11-01 19:28:59 +00:00
// `sum` points to, it was modifying the address stored in the pointer
2024-11-01 19:23:59 +00:00
(*sum) += a[i];
2024-11-01 19:28:59 +00:00
// Missing dereference operators
*avg = *sum / n;
2024-11-01 19:23:59 +00:00
}
```