/* Creating a dynamic array example of using realloc() to create a dynamic array in C useful when you need to store string's of varing sizes without having to hardcode. (block of memory on the heap, malloc() and friends) tested with "valgrind" If the is a better way to do this, bugs, please let me know. Thu Feb 24 18:46:43 CST 2011 - nocon@darkflame.net */ #include #include #include int main() { char **array = NULL; //dynamic array int i; int slen = 0; int m_allocated = 0; //random strings of any length char *strings[] = { "A", "A", "A", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "AAAAAAAA", "AAAAA", "AAA", "AAAAAAAAAAAA", "AA" }; // since there is no was to pull total num elements // from the dynamic array, we need to keep track int count = 0; //get input array total elements/size (just informational) int n_elements = (sizeof(strings)/sizeof(strings[0])); int n_size = sizeof(strings[0]); printf("Input array elements: %d\n",n_elements); printf("Input array size: %d\n\n",n_size); if(n_elements == 0 || n_size == 0) { printf("No data, nothing to do.\n"); return(-1); } // proccess *strings, dynamically grow **array by asigning contents of *strings for(i = 0; i < (sizeof(strings)/sizeof(strings[0])); i++) { printf("Element: %d = %s , addr = %p\n",i, strings[i],&strings[i]); //get strlen of name + \0 char slen += (strlen(strings[i])+1); //printf("Total StrLength: %d\n",slen); //a lot of calls to realloc() cosumes resources so allocate //enough space only when needed if(m_allocated <= slen) { m_allocated = (slen*8); // should be good enough size ;) printf("Allocating %lu bytes to array\n",(m_allocated * (sizeof(char *)))); void *tmp = realloc(array,m_allocated * (sizeof(char *))); if(!tmp) { printf("Could not allocate %d bytes to array!\n",m_allocated); return(-1); } array = tmp; } array[i] = strings[i]; count++; } //print array printf("\n\n"); for(i = 0; i < count; i++) { printf("Element: %d = %s , addr = %p\n",i, array[i],&array[i]); } printf("\n\n"); // all done, be free!! free(array); return 1; }