21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

eak;<br />

case SPC_ARRAY_FOLD:<br />

index = (idx / num_row) + (a->split * (idx % num_row) );<br />

break;<br />

case SPC_ARRAY_FLAT:<br />

index = subarray + (a->split * (idx % num_row));<br />

break;<br />

}<br />

return (index >= a->num_elem ? -1 : index);<br />

}<br />

/* Get a pointer to element 'idx' in array 'subarray' */<br />

void *spc_array_get(spc_array_t *a, int subarray, int idx) {<br />

int index;<br />

if (!a || (index = array_index(a, subarray, idx)) = = -1) return 0;<br />

return (void *)(a->data + (a->sz_elem * index));<br />

}<br />

/* Set element 'idx' in array 'subarray' to the data pointed to by 'src' --<br />

* note that the sz_elem used to initialize the array is used here to copy<br />

* the correct amount of data.<br />

*/<br />

int spc_array_set(spc_array_t *a, int subarray, int idx, void *src) {<br />

int index;<br />

if (!a || !src || (index = array_index(a, subarray, idx)) = = -1)<br />

return 0;<br />

memcpy(a->data + (a->sz_elem * index), src, a->sz_elem);<br />

return 1;<br />

}<br />

/* Free an spc_array_t, including its table of elements */<br />

int spc_array_free(spc_array_t *a) {<br />

if (a) free(a);<br />

return !!a;<br />

}<br />

The function spc_array_split( ) creates a two-dimensional array that is accessed as<br />

if it were an array of a single dimension; all odd-numbered elements are stored in the<br />

first half of the array, and all even-numbered elements are stored in the second half.<br />

For example, an array of five elements with indices numbered zero through four is<br />

conceptually broken up into two arrays where the second and fourth elements are<br />

stored in the first array, and the first, third, and fifth elements are stored in the second<br />

array. The two conceptual arrays are actually stored contiguously in memory.<br />

The effect is a simple reordering of the elements as illustrated in Figure 12-1.<br />

The function spc_array_merge( ) creates a single-dimensional array whose elements<br />

are indexed as if they were two separate arrays; the elements are referenced by an<br />

array number (0 or 1) and an index into that array. The ratio of the size between the<br />

two arrays is used to determine the placement of each element, so that the arrays are<br />

stored in memory as illustrated in Figure 12-2.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Restructuring Arrays | 675

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

Saved successfully!

Ooh no, something went wrong!