简体   繁体   中英

Arrays of char pointers

Here's a function prototype:

void foobar(char* array[]);

But how would I call this function, and with what arguments? Could someone give me a simple example?

Quoting from c-faq (as array name conversion rule to pointers is same in C and C++ both):

Since arrays decay immediately into pointers, an array is never actually passed to a function. You can pretend that a function receives an array as a parameter, and illustrate it by declaring the corresponding parameter as an array:

 void f(char a[]) { ... } 

Interpreted literally, this declaration would have no use, so the compiler turns around and pretends that you'd written a pointer declaration, since that's what the function will in fact receive:

 void f(char *a) { ... } 

Therefore

void foobar(char* array[]);  

is equivalent to

void foobar(char** array);

You need to pass an argumant of type char ** to this function.

Thanks for the reply and comments. Here is what I came up with and it seems to work. Not quite sure why it does, though. Could someone confirm that this is indeed 'correct' code:

void foobar(char* array[]);

void main() {

    char* t[3];
    t[0] = "first";
    t[1] = "second";
    t[2] = "third";
    foobar(t);
}

void foobar(char* array[]) {

    cout << *(array + 0) << endl;
    cout << *(array + 1) << endl;
    cout << *(array + 2) << endl;
}

The output is:

first
second
third

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM