/* * returns a pointer to another arraylist that is the sublist * from the start index to the end index, inclusive. * as this is also an arraylist it should be freed with arraylist_free */ arraylist* arraylist_subList(arraylist *list, int startIndex, int endIndex){ int i; if(startIndex>=list->size||startIndex<0||endIndex>=list->size||endIndex<0||endIndex<startIndex) fprintf(stderr,"your index is out of bounds. size:%d startIndex %d endIndex %d\n",list->size,startIndex,endIndex); int newSize=endIndex-startIndex+1; arraylist *sublist=arraylist_init(list->element_size,newSize); for(i=startIndex;i<=endIndex;++i){ arraylist_addEnd(sublist,arraylist_get(list,i)); } return sublist; }
int main() { ARRAYLIST myArrayList = arraylist_init(); myArrayList->Array = malloc(10*sizeof(int)); int j,k,l,m,n; j = 1; k = 2; l = 5; n = 3; m = 4; arraylist_prepend(myArrayList, &j); printArr(myArrayList); arraylist_append(myArrayList, &k); arraylist_append(myArrayList, &l); arraylist_append(myArrayList, &j); arraylist_append(myArrayList, &n); printArr(myArrayList); arraylist_insert(myArrayList, &m, 1);//insert 4 to index 1 printArr(myArrayList); int u = 8; arraylist_set(myArrayList, &u, 3);// set index 3 as 8 printArr(myArrayList); int *a = arraylist_get(myArrayList, 3);//get address of index 3 printf("get %d\n", *a); arraylist_insert(myArrayList, &m, 10);//insert 4 to index of 10 which does not exist printArr(myArrayList); arraylist_insert(myArrayList, &k, 15);//insert 2 to index of 15 which does not exist printArr(myArrayList); arraylist_set(myArrayList, &k, 7);//set index 7 as 2 printArr(myArrayList); arraylist_remove(myArrayList, 1);//remove index of 9 printArr(myArrayList); arraylist_removeall(myArrayList);//remove everything printArr(myArrayList); arraylist_free(myArrayList); return 1; }
struct arraylist * arraylist_create( uint32_t size ) { struct arraylist * self = NULL; self = (struct arraylist *)malloc( sizeof(struct arraylist) ); if ( self ) { if ( arraylist_init( self, size ) != 0 ) { free( self ); self = NULL; } } return self; }