1

How to use function in C with array of strings? My code:

void test(char **a){
    printf("%s", a[0]);
}
int main(){
    char b[10][10];
    strcpy(b[0],"abc");
    strcpy(b[1],"dfgd");
    test(b);
    return 0;
}

How to make this example of code work?

1
  • 4
    The compiler doesn't know the "real" dimensions of the pointed array in function test. I'm quite surprised that it didn't issue a warning on the line test(b). Change char **a to char a[][10]. Commented Dec 27, 2014 at 16:47

1 Answer 1

4

You can use :

void test(char a[10][10]){
    printf("%s", a[0]);
}

or

void test(char a[][10]){
    printf("%s", a[0]);
}

or

void test(char (*a)[10]){
    printf("%s", a[0]);
}

int main(){
    char b[10][10];
    strcpy(b[0],"abc");
    strcpy(b[1],"dfgd");
    test(b);
    return 0;
}

All three declarations are perfectly equivalent. Although last one is better.

This answer explains it better

Sign up to request clarification or add additional context in comments.

3 Comments

I thought it was very bad :( Because as soon as i asked the question the negative votes were flying like wind :(
You may reopen it (sorry one of the downvotes were mine, and I'm willing to retract them of course if you reopen/undelete the question).
The link is good, but I think you should at least say that all three declarations are perfectly equivalent. I would also add a hint to prefer the last one for clarity.

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.