0

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;
}
1
  • You have to become a three-star programmer and learn about how to emulate pass by reference in c. Commented Dec 24, 2015 at 13:10

1 Answer 1

1

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();
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

And how to change the inside of the function ? *array?
Any advantages over using another pointer in your second example?
@glery Both approaches have their use cases although you could always emulate the second through the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.