Hello, I am trying to use a function to add strings to a 'dynamic array of strings' and wondered if someone might help me fnish this skeletal piece of code.
The function fill_array_x() works, the function fill_array_y() crashes where indicated. I'm looking for a simple fix here - hopefully a missing * or & will wrap it up. Later I will look at using structs, etc. All constructive advice welcome.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *names[] = { "one", "two"};
char **my_str_array = NULL;
/*-------------------------------------*/
int fill_array_x() /* this works for the global string */
{
if (!(my_str_array = malloc(( 2 * sizeof(char*))))) return(-1);
my_str_array[0] = names[0];
my_str_array[1] = names[1];
return 0;
}
/*-------------------------------------*/
int fill_array_y(char ***str_array) /* this generic function has issues */
{
if (!(*str_array = malloc(( 2 * sizeof(char*))))) return(-1);
*str_array[0] = names[0];
*str_array[1] = names[1]; /*crashes here*/
return 0;
}
/*-------------------------------------*/
int main()
{
int i;
/* if (fill_array_x(my_str_array) !=0) return 9; */ /* works */
if (fill_array_y(&my_str_array) !=0) return 9; /* does not work*/
for (i = 0; i < 2; i++)
printf( "'%s'\n", my_str_array[i]);
free(my_str_array);
return 0;
}