I'm learning C after graduation and trying to refresh old skills. I'm currently trying to make a dynamically allocated array that consist of dynamically allocated strings. Below is my code, I am trying to add an adjective to previously initialized array that has the first member as NULL. The last member should always be NULL.
char **addAdjective(char **array, const char *adjective)
{
int i = 0;
int count = 0;
while (*array != NULL){
array++;
count += 1;
}
array = (char**) realloc(*array, sizeof(*array) * (count+2));
int adjectiveLength = strlen(adjective);
array[count] = (char*) malloc(sizeof(const char)*(adjectiveLength + 1));
for (i = 0; i < adjectiveLength; i++){
array[count][i] = adjective[i];
}
array[count][i+1] = '\0';
array[count+1] = NULL;
return array;
}
When I'm calling the above with:
adjectives = addAdjective(adjectives, "beautiful");
adjectives = addAdjective(adjectives, "ugly");
adjectives = addAdjective(adjectives, "sweet");
There seems to be something wrong as when I'm trying to print the array I get nothing..
What could be wrong?
EDIT:
Print function should be okay:
void printAdjectives(char **adjectives)
{
if (!adjectives)
return;
while (*adjectives) {
printf("%s ", *adjectives);
adjectives++;
}
printf("\n");
}
And initialization:
char **initAdjectives(void)
{
char **adjectives = (char **)malloc (1 * sizeof(char *));
*adjectives = NULL;
return adjectives;
}
adjectivesinitially allocated?