Just a quick question ; I'm trying to write a structure which can hold a bunch of strings and grow as more are added.
Usually when using an array of strings I'd implement it like this.
Code:
char **arr = malloc(25 * sizeof(char));
for(size_t i = 0 ; i < 250 ; i++)
arr[i] = malloc(250);
Where 25 is the amount of elements and 250 is the size of the largest string I would want to store?
Without checking the returns value of malloc , this is just to show my thought process. Am I correct when I say that arr is now a pointer to a memory space which represents 25 other char pointers?
Thus arr[2] for example would be the third pointer in the array of pointers , which I could in turn malloc to make space for a string such as above?
Copying a value to this string would then work as
Code:
strcpy(arr[2],"Hello world");
Structure itself:
Code:
typedef struct string_table{
char **data;
size_t entries;
size_t chunkSize;
size_t stringSize;
}STRINGTABLE,stringTable;
Allocating memory for the structure and data.
Code:
STRINGTABLE *constructSt(size_t cs,size_t ss){
STRINGTABLE *st = malloc(sizeof(STRINGTABLE));
if(!st)
return NULL;
st->chunkSize = cs;
st->stringSize = ss;
st->entries = 0;
st->data = malloc(cs);
if(!st->data)
return NULL;
for(size_t i =0 ; i < cs ; i++){
(st->data[i]) = malloc(ss);
if(!(st->data[i]))
return NULL;
}
return st;
}