Answer the question
In order to leave comments, you need to log in
How to add a string to a dynamic array of strings in SI?
I am writing a function that adds a string to an array of strings.
char **add_string(char **array, const char *string)
{
int i = 0;
while (array[i] != NULL){
i++;
}
array = realloc(array, (i + 1) * sizeof(char *));
array[i] = malloc((strlen(string) + 1));
strcpy(array[i], string);
return array;
}
char **init_array(void)
{
char **array = malloc(sizeof(char *));
array[0] = NULL;
return array;
}
Answer the question
In order to leave comments, you need to log in
array = realloc(array, (i + 1) * sizeof(char *)); array[i] = malloc((strlen(string) + 1));
array = realloc(array, (i + 2) * sizeof(char *));
array[i] = malloc((strlen(string) + 1));
array[i + 1] = NULL;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question