dynlist.c revision 8db30ca8
1/* dynlist.c: Dynamic lists and buffers in C. 2 * created 1999-Jan-06 15:34 jmk 3 * autodate: 1999-Dec-24 00:12 4 * 5 * by Jim Knoble <jmknoble@pobox.com> 6 * Copyright � 1999 Jim Knoble 7 * 8 * Disclaimer: 9 * 10 * The software is provided "as is", without warranty of any kind, 11 * express or implied, including but not limited to the warranties of 12 * merchantability, fitness for a particular purpose and 13 * noninfringement. In no event shall the author(s) be liable for any 14 * claim, damages or other liability, whether in an action of 15 * contract, tort or otherwise, arising from, out of or in connection 16 * with the software or the use or other dealings in the software. 17 * 18 * Permission to use, copy, modify, distribute, and sell this software 19 * and its documentation for any purpose is hereby granted without 20 * fee, provided that the above copyright notice appear in all copies 21 * and that both that copyright notice and this permission notice 22 * appear in supporting documentation. 23 */ 24 25#include <stdio.h> 26#include <stdlib.h> 27 28#include "dynlist.h" 29 30#define LIST_CHUNK_SIZE 512 31#define BUF_CHUNK_SIZE 512 32 33/* For lists of pointers cast to char *. */ 34int append_to_list(char ***list_ptr, int *list_len, int *i, char *item) 35{ 36 char **tmp_ptr; 37 38 if (*i >= *list_len) 39 { 40 *list_len += LIST_CHUNK_SIZE; 41 tmp_ptr = realloc(*list_ptr, (sizeof(**list_ptr) * *list_len)); 42 if (NULL == tmp_ptr) 43 { 44 return(APPEND_FAILURE); 45 } 46 *list_ptr = tmp_ptr; 47 } 48 (*list_ptr)[*i] = item; 49 (*i)++; 50 return(APPEND_SUCCESS); 51} 52 53/* For single-dimensional buffers. */ 54int append_to_buf(char **buf, int *buflen, int *i, int c) 55{ 56 char *tmp_buf; 57 58 if (*i >= *buflen) 59 { 60 *buflen += BUF_CHUNK_SIZE; 61 tmp_buf = realloc(*buf, (sizeof(**buf) * *buflen)); 62 if (NULL == tmp_buf) 63 { 64 return(APPEND_FAILURE); 65 } 66 *buf = tmp_buf; 67#ifdef DEBUG 68 printf("-->Allocated buffer of size %d\n", *buflen); 69#endif /* DEBUG */ 70 } 71 (*buf)[*i] = (char) c; 72 (*i)++; 73 return(APPEND_SUCCESS); 74} 75 76