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

61 lines
1.7 KiB
Markdown
Raw Normal View History

2024-11-19 21:10:06 +00:00
> **4.** Suppose that the following declarations are in effect:
2024-11-19 21:05:06 +00:00
```c
2024-11-19 21:10:06 +00:00
struct point {int x, y; };
struct rectangle { struct point upper_left, lower_right; };
struct rectangle *p;
2024-11-19 21:05:06 +00:00
```
2024-11-19 21:10:06 +00:00
> Assume that we want `p` to point to a rectangle structure whose upper left corner is at $(10, 25)$, and whose lower right corner is at $(20, 15)$. Write a series of statements that allocate such a structure and initialize it as indicated.
2024-11-19 21:05:06 +00:00
2024-11-19 21:15:06 +00:00
```c
struct rectangle rect = { { 10, 25 }, { 20, 15 } };
p = ▭
```
---
2024-11-19 21:20:06 +00:00
> **5.** Suppose that `f` and `p` are declared as follows:
```c
struct {
union {
char a, b;
int c;
} d;
int e[5];
} f, *p = &f;
2024-11-19 21:25:06 +00:00
```
> Which of the following statements are legal?
(a) `p->b = ' ';`
2024-11-20 03:57:20 +00:00
(b) `p->e[3] = 10;` - **Legal**
(c) `(*p).d.a = '*';` - **Legal**
(d) `p->d->c = 20;`
---
> **7.** The following loop is supposed to delete all nodes from a linked list and release the memory that they occupy. Unfortunately, the loop is incorrect. Explain what's wrong with it and show how to fix the bug.
```c
for (p = first; p != NULL; p = p->next)
free(p);
```
2024-11-20 04:02:30 +00:00
The above loop won't function because it deallocates the entry, then attempts to access the pointer to the next item, *after* it's already been freed.
A functional example might look like this:
```c
struct entry* p = first;
2024-11-20 04:26:03 +00:00
while (p != NULL) {
void *current = p;
p = p->next;
free(p);
}
```
---
2024-11-20 04:02:30 +00:00
2024-11-20 04:31:02 +00:00
> **9.** True or false: If `x` is a structure and `a` is a member of that structure, then `(&x)->a` is the same as `x.a`. Justify your answer.
**True**: The arrow operator is used to access a member of a struct through a pointer. `(&x)` creates a pointer to the `x` struct, therefore the arrow operator can be used to access fields on `x`.
---
> **13.**