Could anyone explain me how to pass 2D array of strings to a function using another pointer ? I want to pass array to a function FILL using pointer. In that function I want to copy a string to an array.
void FILL(char **array) {
char buffer[20] = "Hi my name is John."
array = (char**) malloc ( 1 * sizeof(char*));
for ( i = 0; i < 1; i++ ) {
array[i] = (char*) malloc ( 20 * sizeof(char*));
strcpy(array[i],buffer);
}
}
int main()
{
char **array = NULL;
FILL(array);
return 0;
}
Just use a triple pointer to char (and enjoy being called a three-star programmer):
void FILL(char ***array);
int main()
{
char **array;
FILL(&array);
return 0;
}
Alternatively, consider returning the allocated memory segment in FILL
instead of passing a pointer:
char **FILL() {
char **array = ...;
...
return array;
}
int main()
{
char **array = FILL();
...
}