This is a sample of using AllocateDynArrayEntry() to add elements to a dynamic array. Please don't be confused by the high amount of debug output this sample produces, just pay attention to comments in main() to better understand what this sample does.
#include <nwdynarr.h>
#include <stdio.h>
#include <stdlib.h>
static void* my_realloc( void* p, size_t n) {
printf( "realloc called, p = %X, n = %d\n", p, n);
return realloc( p, n);
}
GEN_DYNARRAY_BLOCK( int, DynArrTest, DEFINE( my_realloc, 3));
static void disp_dyn_arr( struct DynArrTestStruct* p_DynArrTest) {
size_t i;
printf( "DABnumSlots = %d, DABnumEntries = %d, DABarrayP =",
p_DynArrTest -> DABnumSlots,
p_DynArrTest -> DABnumEntries);
for ( i = 0; i < p_DynArrTest -> DABnumSlots; ++i) {
printf( " %d", p_DynArrTest -> DABarrayP[ i]);
}
puts( "");
}
int main() {
int i;
/* add 5 elements to the array */
puts( "Adding ...");
for ( i = 0; i < 5; ++i) {
int index = AllocateDynArrayEntry( &DynArrTest);
printf( "index = %d, ", index);
disp_dyn_arr( &DynArrTest);
}
/* delete 3 elements from the beginning of the array */
puts( "Deleting ...");
for ( i = 0; i < 3; ++i) {
DeallocateDynArrayEntry( &DynArrTest, i);
disp_dyn_arr( &DynArrTest);
}
/* add 5 more elements to the array. Note that the 3 deleted elements in the array are reused */
puts( "Adding ...");
for ( i = 0; i < 5; ++i) {
int index = AllocateDynArrayEntry( &DynArrTest);
printf( "index = %d, ", index);
disp_dyn_arr( &DynArrTest);
}
free( DynArrTest.DABarrayP);
return EXIT_SUCCESS;
}
© 2008 Novell, Inc. All Rights Reserved.