typedef struct ArrayList
{
// We will store an array of strings (i.e., an array of char arrays)
char **array;
// Size of list (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;
} ArrayList;
The following function is supposed to dynamically allocate memory for an array of strings supported by a header file which contains a struct (see above):
void panic(char *s)
{
fprintf(stderr, "%s", s);
exit(1);
}
ArrayList *createArrayList(int length){
ArrayList *n = malloc(sizeof(ArrayList));
int initial = 0, i;
if (length > DEFAULT_INIT_LEN)
{
n->array = (char **)malloc(length * sizeof(int*));
n->capacity = length;
for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}
}
else
{
n->array = (char **)malloc(DEFAULT_INIT_LEN * sizeof(int*));
n->capacity = DEFAULT_INIT_LEN;
for (i = 0; i< n->capacity; i++)
{
n->array[i] = NULL;
}
}
if (n->array == NULL)
panic("ERROR: out of memory in Mylist!\n");
n->size = initial;
printf("-> Created new ArrayList of size %d\n", n->capacity);
return n;
}
Then I have another function that is supposed to print all of the strings currently in the newly allocated array created by the createArrayList function:
void printArrayList(ArrayList *list)
{
int i;
for(i=0; i<list->capacity; i++)
{
if (list->array[i] == NULL)
printf("(empty list)\n");
else
printf("%s\n",list->array[i]);
}
}
When I implement the printArrayList function (above) in my main function, the output is:
-> Created ArrayList of size 10
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
However, if i insert strcpy(n->array[1], "apple");
in the createArrayList function as a means of testing the 2D array's ability to hold strings the output is:
-> Created ArrayList of size 10
...and then it crashes
So my question is what am I doing wrong? Am I incorrectly allocating memeory for my array? I want to get it so the output is:
-> Created ArrayList of size 10
(empty list)
apple
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)