27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 16 | Low Level<br />

16.10 Write a function called my2DAlloc which allocates a two dimensional array. Minimize<br />

<strong>the</strong> number of calls to malloc <strong>and</strong> make sure that <strong>the</strong> memory is accessible by <strong>the</strong><br />

notation arr[i][j].<br />

SOLUTION<br />

We will use one call to malloc.<br />

pg 82<br />

Allocate one block of memory to hold <strong>the</strong> row vector <strong>and</strong> <strong>the</strong> array data. The row vector will<br />

reside in rows * sizeof(int*) bytes. The integers in <strong>the</strong> array will take up ano<strong>the</strong>r rows * cols *<br />

sizeof(int) bytes.<br />

Constructing <strong>the</strong> array in a single malloc has <strong>the</strong> added benefit of allowing disposal of <strong>the</strong><br />

array with a single free call ra<strong>the</strong>r than using a special function to free <strong>the</strong> subsidiary data<br />

blocks.<br />

1 #include <br />

2<br />

3 int** My2DAlloc(int rows, int cols) {<br />

4 int header = rows * sizeof(int*);<br />

5 int data = rows * cols * sizeof(int);<br />

6 int** rowptr = (int**)malloc(header + data);<br />

7 int* buf = (int*)(rowptr + rows);<br />

8 int k;<br />

9 for (k = 0; k < rows; ++k) {<br />

10 rowptr[k] = buf + k*cols;<br />

11 }<br />

12 return rowptr;<br />

13 }<br />

CareerCup.com<br />

2 4 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!