Hello,
I'm trying to create "SmartArray" in C, which is a struct defined like this:
Code:
typedef struct SmartArray{
//will store an array of strings
char **array;
// Size of array (i.e., number of elements that have been added to the array)
int size;
// Length of the array (i.e., the array's current maximum capacity)
int capacity;
} SmartArray;
Now, first I allocate room for only 1 string(only pointers, not memory for strings)...
Code:
SmartArray *createSmartArray(int length){
SmartArray* SA = NULL;
//there are checks for malloc failure but I omitted them now to make the code clearer
SA = (SmartArray*)malloc(sizeof(SmartArray));
SA->array = (char**)malloc(sizeof(char*)*1);
SA->size = 0;
SA->capacity = length;
return SA;
}
The plan is that all of the other pointers and memory be allocated when something needs to be added to this struct's array.
This function should insert strings into the array:
Code:
char *put(SmartArray *smarty, char *str){
if(smarty == NULL || str == NULL)
return NULL;
if((strlen(str) + getCurrentLength(smarty)) >= smarty->capacity){
smarty = expandSmartArray(smarty, smarty->capacity*2 + 1);
}
smarty->array[smarty->size] = (char*)malloc(sizeof(char)*(strlen(str) + 1));
if(smarty->array[smarty->size] == NULL)
{
printf("Couldn't allocate space for new string\n");
return NULL;
}
strcpy(smarty->array[smarty->size], str);
smarty->size += 1;
return smarty->array[smarty->size - 1];
}
This seems to work fine, as long as the initial capacity doesn't have to be changed, but when it does, segfault occurs. Here is my expandSmartArray function:
Code:
SmartArray *expandSmartArray(SmartArray *smarty, int length){
int i;
if(length <= smarty->capacity)
return smarty;
SmartArray* newSmarty = (SmartArray*)malloc(sizeof(SmartArray));
//if any of the MALLOC's fail, return NULL, again omitted from code
newSmarty->array = (char**)malloc(sizeof(char*)*smarty->size);
for(i = 0; i < smarty->size; i++)
{
newSmarty->array[i] = (char*)malloc(sizeof(char)*(strlen(smarty->array[i]) + 1));
strcpy(newSmarty->array[i], smarty->array[i]);
}
newSmarty->size = smarty->size;
newSmarty->capacity = length;
smarty = destroySmartArray(smarty);
printf("Expanded SmartArray to size %d\n", newSmarty->capacity);
return newSmarty;
}
Does anyone have any idea how can I make this work?
My main is really simple at this point:
Code:
SmartArray *smarty1 = createSmartArray(20);
while (fscanf(file, "%s", buffer) != EOF)
put(smarty1, buffer);