Chapter 2: Arrays and Structures
Multiple Choice · Array ADT
Question 1: Indexing with a Pointer
int a[8]; int *p = a + 2; as defined, which elements are p[3] and *(p - 1)?
C: p points to a[2]. p[3] ≡ *(p + 3) ≡ a[2 + 3] = a[5]; *(p - 1) = a[1]. Pointer arithmetic counts elements: p + 3 is 3·sizeof(int) bytes ahead. A and D, in computing p[3], assume p points to the start of a; B and D take *(p - 1) to be a[2].
Multiple Choice · Array ADT
Question 2: sizeof in a Parameter
int is 4 bytes and a pointer is 8 bytes on this system. What does the program print?
void f(int a[]) { printf("%zu\n", sizeof a / sizeof a[0]); } int main(void) { int d[10]; printf("%zu ", sizeof d / sizeof d[0]); f(d); return 0; }
B: In main, d is a real array: 40 / 4 = 10. The parameter int a[] is the same as int *a; sizeof a gives the size of a pointer (8): 8 / 4 = 2. The array is not copied into the function, only its address is passed; that is why the size is sent as a separate parameter. The compiler also warns about this line.
Output Question · Array ADT
Question 3: Pointer Arithmetic
What does the fragment print? What would (char *)q - (char *)(d + 1) be (int is 4 bytes)?
int d[] = {10, 20, 30, 40, 50}; int *p = d + 1, *q = &d[4]; printf("%td\n", q - p); printf("%d\n", *p + 1); printf("%d\n", *(p + 1)); p += 2; *p = 7; printf("%d %d\n", d[3], p[-1]);
Show answer
3 21 30 7 30
q - p: d[4] and d[1] are 3 elements apart (not bytes).*p + 1: first*p= 20, then + 1 → 21.*(p + 1)is d[2] = 30; the parentheses change the order of evaluation.p += 2→ p = &d[3];*p = 7changes d[3].p[-1]= d[2] = 30.
The byte difference is 3 · 4 = 12: char * arithmetic counts bytes.
Multiple Choice · Dynamic Arrays
Question 4: Growing with realloc
The dynamic array of n elements, a, is to be enlarged to m > n elements. Which option keeps the old elements and, if memory cannot be allocated, does not lose the old block?
B: If realloc fails it returns NULL and the old block stays in place, so the result must first go into a temporary variable. In A, NULL overwrites a and the old block leaks. C does not copy the old elements and does not release the old block; D destroys the old data.
Step-by-Step Trace · Dynamic Arrays
Question 5: An Array That Grows by a Fixed Amount
append does not double the capacity but adds 2. How many copies are made when 6 elements are appended to an empty array? How does the cost grow for n appends?
Empty array {NULL, 0, 0}. 6, 1, 8, 3, 5, 2 will be appended in turn.
Full (0 == 0): cap 0 → 2. realloc from NULL behaves like malloc. 6 is written.
There is room: 1 is written directly.
Full: cap 2 → 4; realloc moves the 2 old elements to the new block.
There is room: 3 is written.
Full: cap 4 → 6; 4 more copies.
For 6 appends: 2 + 4 = 6 copies. One growth every 2 appends: ≈ n²/4 copies for n appends (249,500 for n = 1000) → O(n²); with doubling it never exceeds 1023.
int append(DynArray *d, int x) { if (d->size == d->cap) { int ncap = d->cap + 2; /* fixed */ int *t = realloc(d->data, ncap * sizeof *t); if (t == NULL) return 0; d->data = t; d->cap = ncap; } d->data[d->size++] = x; return 1; }
Spot the Bug · Dynamic Arrays
Question 6: Releasing a 2D Array
array2d(3, 4): what is wrong with this function that releases the array allocated by it? How should it be written, and how many free calls are needed in total?
void free2d(int **x, int rows) { int i; free(x); for (i = 0; i < rows; i++) free(x[i]); }
Show answer
free(x) releases the pointer array; reading x[i] afterwards is access to freed memory (undefined behavior). The program often seems to work, which makes this bug more insidious.
void free2d(int **x, int rows) { int i; for (i = 0; i < rows; i++) free(x[i]); /* rows first */ free(x); /* then the array */ }
array2d(3, 4) makes 1 + 3 = 4 malloc calls; 4 free calls are needed (verified with a counter). If only free(x) were written, the rows would leak.
Multiple Choice · Multidimensional Arrays
Question 7: Column-Major Address
float m[6][5] starts at address α = 1000, sizeof(float) = 4. If the array were stored in column-major order, what would &m[2][3] be?
D: In column-major order there are 3 whole columns (3 · 6 = 18 elements) before the element, plus 2 elements in its own column: 1000 + 20 · 4 = 1080. A is row-major (the one C uses): 1000 + (2 · 5 + 3) · 4 = 1052. B uses the row length (5) instead of the column length.
Classic Question · Multidimensional Arrays
Question 8: Relative Position with Horner
char K[4][3][6]; starts at address 500. K[2][1][4]: find its relative position by Horner's method. What is the address, how many multiplications are made, and which dimension plays no part?
Show answer
t = 2 → t = 2 · 3 + 1 = 7 → t = 7 · 6 + 4 = 46. char is 1 byte, so the address is 500 + 46 = 546.
n − 1 = 2 multiplications are made. The first dimension (4) never enters the formula; it is needed only for bounds checking. The explicit formula gives the same result: 2 · 3 · 6 + 1 · 6 + 4 = 46. In a real C array, &K[2][1][4] - &K[0][0][0] gives 46.
Multiple Choice · Triangular and Band Matrices
Question 9: Upper Triangular Matrix
The elements of a 5 × 5 upper triangular matrix (j ≥ i) are written row by row into a one-dimensional array. a13 is at which index of this array?
A: Row 0 has 5 elements (indices 0–4); in row 1, a11, a12, a13 go to indices 5, 6, 7. Formula: i·n − i(i−1)/2 + (j − i) = 5 − 0 + 2 = 7. B is the lower triangular formula (i(i+1)/2 + j); C is the position in the full matrix (i·n + j).
Step-by-Step Trace · Triangular and Band Matrices
Question 10: Access in a Band Matrix
A band matrix with n = 5, a = 2, b = 3 (diagonal included) was built with band_build. For (3, 2), (1, 3), (2, 2), (0, 4) and (4, 1), what does band_get return?
The bands are −1, 0, 1, 2 (lengths 4, 5, 4, 3) → 16 elements, start = [0, 4, 9, 13]. The number in each cell is the band number j − i.
d32: j − i = −1 → lower. i − j = 1 < 2 → start[−1 + 1] + j = 0 + 2 = 2.
d13: j − i = 2 < b = 3 → upper band: start[2 + 1] + i = 13 + 1 = 14.
The diagonal is also in the 'lower' branch: start[0 + 1] + j = 4 + 2 = 6.
d04: j − i = 4 ≥ b → outside the band, upper constant region: −1.
d41: i − j = 3 ≥ a = 2 → lower constant region: −2. Every call does a constant number of operations: O(1).
int band_get(int i, int j, int n, int a, int b, int start[]) { if (i < 0 || j < 0 || i >= n || j >= n) return -3; else if (j - i >= 1) { /* upper */ if (j - i < b) return start[j - i + a - 1] + i; else return -1; } else if (i - j < a) /* lower */ return start[j - i + a - 1] + j; else return -2; }
Multiple Choice · Triangular and Band Matrices
Question 11: Number of Elements in the Bands
Only the main diagonal and the two bands below it are stored in a 6 × 6 matrix (a = 3, b = 1). How many elements does the band array hold?
D: The band lengths are 4 + 5 + 6 = 15; formula n(a + b − 1) − a(a − 1)/2 − b(b − 1)/2 = 18 − 3 − 0 = 15. A counts every band as length n; the lower bands get one shorter for each step away from the diagonal.
Multiple Choice · Triangular and Band Matrices
Question 12: Short-Circuit Evaluation
a is an array of n elements and i == n. In which condition below is the out-of-bounds element a[n] read?
C: & is bitwise AND: both operands are evaluated, with no short-circuiting. && and || are evaluated left to right: in A, when i < n, the right side is never evaluated; in B, evaluation stops when i >= n is true. A and D are equally safe.
Output Question · Structures
Question 13: Structure Assignment
How does structure assignment copy the fields? What does the fragment print?
typedef struct { char name[8]; int *grade; } record; int n1 = 70; record a = {"Ali", &n1}, b; b = a; strcpy(b.name, "Can"); *b.grade = 90; printf("%s %d\n", a.name, *a.grade);
Show answer
Output: Ali 90.
b = acopies field by field: thenamearray's contents are copied into b, but of thegradepointer only the value (the address) is.strcpy(b.name, "Can")changes only b's own array; a.name stays "Ali".a.gradeandb.gradepoint to the samen1;*b.grade = 90changes n1, so 90 is also read through a.
This is called a shallow copy: in structures with pointer fields, the pointed-to data is shared. *b.grade means *(b.grade); the . operator has higher precedence than *.
Multiple Choice · Structures
Question 14: Alignment and sizeof
int is 4 bytes and 4-byte aligned. For struct { char a; int b; char c; }, what is sizeof typically?
A: After a, 3 padding bytes are added to align b to a multiple of 4 (0: a, 4–7: b, 8: c); the structure size must also be a multiple of the widest alignment: 9 → 12. C is the raw sum of the fields. B is obtained when the fields are written in the order { int b; char a, c; } (4 + 1 + 1 → 8).
Step-by-Step Trace · Strings
Question 15: Reversing a String
reverse changes the string "kalem" step by step. What does the program print?
strlen = 5 → q points to the last letter; '\0' must stay in place.
p < q: 'k' and 'm' swap.
p++, q-- → 1 < 3: 'a' and 'e' swap.
p == q: the middle 'l' stays in place, the loop ends.
n/2 swaps → O(n). For an empty string q would be s − 1; creating a pointer before the array is undefined, so strlen(s) == 0 must be checked first.
void reverse(char *s) { char *p = s, *q = s + strlen(s) - 1, t; while (p < q) { t = *p; *p = *q; *q = t; p++; q--; } } /* main: */ char s[] = "kalem"; reverse(s); printf("%s\n", s);
Spot the Bug · Strings
Question 16: Copying a String
The code below has three bugs. What are they, and how should it be written?
char *copy_of(const char *name) { char *s = malloc(strlen(name)); strcpy(s, name); return s; } /* main: */ char *k = copy_of("Ali"); if (k == "Ali") printf("same\n");
Show answer
malloc(strlen(name))leaves no room for'\0': 3 bytes for "Ali",strcpywrites 4 → overflow. Usestrlen(name) + 1.mallocis not checked againstNULL.k == "Ali"compares addresses, not contents. Usestrcmp(k, "Ali") == 0.
char *s = malloc(strlen(name) + 1); if (s == NULL) return NULL; strcpy(s, name); /* ... */ if (strcmp(k, "Ali") == 0) printf("same\n"); free(k);
Release the copy with free.
Coding Question · Matrix Operations
Question 17: Matrix Multiplication on Flat Arrays
The m × n matrix a and the n × p matrix b are stored row-major in one-dimensional arrays. The m × p product is written to c. Write mult. How many multiplications does multiplying 3 × 4 by 4 × 2 take?
Show answer
void mult(const int *a, const int *b, int *c, int m, int n, int p) { int i, j, k; for (i = 0; i < m; i++) for (j = 0; j < p; j++) { int s = 0; for (k = 0; k < n; k++) s += a[i * n + k] * b[k * p + j]; c[i * p + j] = s; } }
aik in row-major order is at a[i * n + k] (i whole rows precede it). Each of the m·p cells of c needs n products: 3 · 4 · 2 = 24 multiplications, 6 cells → O(m·n·p); for square matrices O(n³).