user3885616
user3885616

Reputation:

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?

Upvotes: 0

Views: 77

Answers (2)

user3885616
user3885616

Reputation:

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

Upvotes: 0

haccks
haccks

Reputation: 105992

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.

Upvotes: 7

Related Questions