开发者

Passing an array of strings to a C function by reference

I am having a hard time passing an array of strings to a function by reference.

  char* parameters[513]; 

Does t开发者_StackOverflowhis represent 513 strings? Here is how I initialized the first element:

 parameters[0] = "something";

Now, I need to pass 'parameters' to a function by reference so that the function can add more strings to it. How would the function header look and how would I use this variable inside the function?


You've already got it.

#include <stdio.h>
static void func(char *p[])
{
    p[0] = "Hello";
    p[1] = "World";
}
int main(int argc, char *argv[])
{
    char *strings[2];
    func(strings);
    printf("%s %s\n", strings[0], strings[1]);
    return 0;
}

In C, when you pass an array to a function, the compiler turns the array into a pointer. (The array "decays" into a pointer.) The "func" above is exactly equivalent to:

static void func(char **p)
{
    p[0] = "Hello";
    p[1] = "World";
}

Since a pointer to the array is passed, when you modify the array, you are modifying the original array and not a copy.

You may want to read up on how pointers and arrays work in C. Unlike most languages, in C, pointers (references) and arrays are treated similarly in many ways. An array sometimes decays into a pointer, but only under very specific circumstances. For example, this does not work:

void func(char **p);
void other_func(void)
{
    char arr[5][3];
    func(arr); // does not work!
}


char* parameters[513]; is an array of 513 pointers to char. It's equivalent to char *(parameters[513]).

A pointer to that thing is of type char *(*parameters)[513] (which is equivalent to char *((*parameters)[513])), so your function could look like:

void f( char *(*parameters)[513] );

Or, if you want a C++ reference:

void f( char *(&parameters)[513] );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜