array - if (nguys > a->max) { result...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
/* * Array of void pointers. See array.h. */ #include <types.h> #include <kern/errno.h> #include <lib.h> #include <array.h> struct array { int num; int max; void **v; }; struct array * array_create(void) { struct array *a = kmalloc(sizeof(struct array)); if (a==NULL) { return NULL; } a->v = NULL; a->num = 0; a->max = 0; return a; } int array_getnum(struct array *a) { return a->num; } void * array_getguy(struct array *a, int index) { assert(a->num <= a->max); assert(index >=0 & index num); return a->v[index]; } int array_preallocate(struct array *a, int nguys) { void **newv; int i; int newmax = a->max; assert(a->num >=0 & a->num max); while (nguys > newmax) { newmax = (newmax+1)*2; } newv = kmalloc(newmax * sizeof(void *)); if (newv==NULL) { return ENOMEM; } a->max = newmax; for (i=0; i<a->num; i++) newv[i] = a->v[i];
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
if (a->v!=NULL) { kfree(a->v); } a->v = newv; return 0; } int array_setsize(struct array *a, int nguys) { int result; assert(a->num >=0 & a->num max);
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: if (nguys &gt; a-&gt;max) { result = array_preallocate(a, nguys); if (result) { return result; } } else if (nguys==0 &amp;&amp; a-&gt;max &gt; 16) { assert(a-&gt;v!=NULL); kfree(a-&gt;v); a-&gt;v = NULL; a-&gt;max = 0; } a-&gt;num = nguys; return 0; } void array_setguy(struct array *a, int index, void *ptr) { assert(a-&gt;num &lt;= a-&gt;max); assert(index &gt;=0 &amp;&amp; index &lt; a-&gt;num); a-&gt;v[index] = ptr; } int array_add(struct array *a, void *guy) { int ix, result; ix = a-&gt;num; result = array_setsize(a, ix+1); if (result) { return result; } a-&gt;v[ix] = guy; return 0; } void array_remove(struct array *a, int index) { int nmove; assert(a-&gt;num &lt;= a-&gt;max); assert(index &gt;=0 &amp;&amp; index &lt; a-&gt;num); nmove = a-&gt;num - (index + 1); memmove(a-&gt;v+index, a-&gt;v+index+1, nmove*sizeof(void *)); a-&gt;num--; } void array_destroy(struct array *a) { if (a-&gt;v) kfree(a-&gt;v); kfree(a); }...
View Full Document

This note was uploaded on 11/10/2009 for the course CS 536 taught by Professor Lums during the Spring '09 term at Indiana.

Page1 / 3

array - if (nguys &amp;amp;gt; a-&amp;amp;gt;max) { result...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online