Chapter 2: Arrays and Structures

Data Structures and Algorithms with C · Study Questions
Arrays and pointersDynamic arrayAddress calculationTriangular and band matricesstruct and alignmentStringsMatrix multiplication
Sercan KÜLCÜ · Giresun University · Computer Engineering

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 = 7 changes 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?

data (cap = 0, size = 0)NULL

Empty array {NULL, 0, 0}. 6, 1, 8, 3, 5, 2 will be appended in turn.

data (cap = 2, size = 1)6010 elements copied

Full (0 == 0): cap 0 → 2. realloc from NULL behaves like malloc. 6 is written.

data (cap = 2, size = 2)6011

There is room: 1 is written directly.

data (cap = 4, size = 3)60118232 elements copied

Full: cap 2 → 4; realloc moves the 2 old elements to the new block.

data (cap = 4, size = 4)60118233

There is room: 3 is written.

data (cap = 6, size = 5)601182335454 elements copied

Full: cap 4 → 6; 4 more copies.

data (cap = 6, size = 6)601182335425

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?

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

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.

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

d32: j − i = −1 → lower. i − j = 1 < 2 → start[−1 + 1] + j = 0 + 2 = 2.

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

d13: j − i = 2 < b = 3 → upper band: start[2 + 1] + i = 13 + 1 = 14.

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

The diagonal is also in the 'lower' branch: start[0 + 1] + j = 4 + 2 = 6.

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

d04: j − i = 4 ≥ b → outside the band, upper constant region: −1.

0123400121-10122-10123-1014-10band[] (start = [0, 4, 9, 13])0123456789101112131415

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 = a copies field by field: the name array's contents are copied into b, but of the grade pointer only the value (the address) is.
  • strcpy(b.name, "Can") changes only b's own array; a.name stays "Ali".
  • a.grade and b.grade point to the same n1; *b.grade = 90 changes 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?

k0a1l2e3m4\05pq

strlen = 5 → q points to the last letter; '\0' must stay in place.

m0a1l2e3k4\05pq

p < q: 'k' and 'm' swap.

m0e1l2a3k4\05pq

p++, q-- → 1 < 3: 'a' and 'e' swap.

m0e1l2a3k4\05p,q

p == q: the middle 'l' stays in place, the loop ends.

m0e1l2a3k4\05

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", strcpy writes 4 → overflow. Use strlen(name) + 1.
  • malloc is not checked against NULL.
  • k == "Ali" compares addresses, not contents. Use strcmp(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³).

The End

Chapter 2: Arrays and Structures: Study Questions
Lecture slides: Chapter 2: Arrays and Structures · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.