If you want to make a variable-sized array of fixed-size strings:
char **arr = calloc(len, 50 * sizeof(char));
Don't forget to free the memory!
for(unsigned long i = 0; i < len; ++i)
free(*arr++);
You're not going to be dynamically pushing elements, are you? If so, we're going to have to get a bit more complicated. (I'd add a StringArray::capacity
, to speed up push
, but I don't want to overcomplicate things... Seeing as how I suck at C, if you look at the comments below. ;))
struct StringArray
{
char** arr;
unsigned long len = 0;
};
StringArray StringArray_init(char** arr = NULL, unsigned long len = NULL)
{
StringArray a;
a.arr = arr;
a.len = len;
return(a);
}
void StringArray_push(StringArray *a, char* str)
{
if(len == 0)
{
a.arr = StringArrayInit(malloc(sizeof(char*)), 1);
}
else
{
a.len++;
}
a.arr = realloc(a.arr, a.len * sizeof(char*));
a.arr[a.len - 1] = malloc((strlen(str) + 1) * sizeof(char));
strcpy(a.arr[a.len - 1], str);
}
void StringArray_free(StringArray a)
{
for(unsigned long i = 0; i < a.len; ++i)
free(a.arr[i]);
}
StringArray szArr = StringArray_init();
StringArray_push(&szArr, "This is a string.");
StringArray_free(szArr);
It's a heck lot easier with C++. :)
std::vector<std::string> arr;
arr.push_back("This is a string.");