25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions 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 and 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 />

CareerCup com<br />

pg 82<br />

Allocate one block of memory to hold <strong>the</strong> row vector and <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 />

2 4 8

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

Saved successfully!

Ooh no, something went wrong!