21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

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.

arrays. This array type will hide the management of the array restructuring from the<br />

programmer.<br />

typedef enum {<br />

SPC_ARRAY_SPLIT, SPC_ARRAY_MERGE, SPC_ARRAY_FOLD, SPC_ARRAY_FLAT<br />

} spc_array_type;<br />

typedef struct {<br />

spc_array_type type;<br />

int sz_elem;<br />

int num_elem;<br />

int split;<br />

unsigned char data[1];<br />

} spc_array_t;<br />

Four functions—spc_array_split( ), spc_array_merge( ), spc_array_fold( ), and spc_<br />

array_flat( )—are provided for creating arrays. The spc_array_get( ) function<br />

retrieves an element from an array, and the spc_array_set( ) function sets an element<br />

in the array. Use spc_array_free( ) to destroy an array.<br />

#include <br />

#include <br />

/* Create a split array of num_elem elements, each of size sz_elem */<br />

spc_array_t *spc_array_split(int sz_elem, int num_elem) {<br />

double size;<br />

spc_array_t *a;<br />

size = (((double)sz_elem * (double)num_elem) / 2) + (double)sizeof(spc_array_t);<br />

if (size > (double)INT_MAX) return 0;<br />

if (!(a = (spc_array_t *)calloc((size_t)size, 1))) return 0;<br />

a->type = SPC_ARRAY_SPLIT;<br />

a->sz_elem = sz_elem;<br />

a->num_elem = num_elem;<br />

a->split = 2; /* array is split into 2 arrays */<br />

return a;<br />

}<br />

/* Create two merged arrays with num_first elements in array 1 and num_second<br />

* elements in array 2<br />

*/<br />

spc_array_t *spc_array_merge(int sz_elem, int num_first, int num_second) {<br />

double size;<br />

spc_array_t *a;<br />

size = (((double)num_first + (double)num_second) * (double)sz_elem) +<br />

(double)sizeof(spc_array_t);<br />

if (!num_first || size > (double)INT_MAX) return 0;<br />

if (!(a = (spc_array_t *)calloc((size_t)size, 1))) return 0;<br />

a->type = SPC_ARRAY_MERGE;<br />

a->sz_elem = sz_elem;<br />

a->num_elem = num_first + num_second;<br />

a->split = num_first / num_second;<br />

if (!a->split) a->split = (num_second / num_first) * -1;<br />

return a;<br />

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

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

Restructuring Arrays | 673

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

Saved successfully!

Ooh no, something went wrong!