Passing an array of strings to a C function by reference

不羁岁月 提交于 2019-12-12 08:07:47

问题


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

  char* parameters[513]; 

Does this 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?


回答1:


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!
}



回答2:


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] );


来源:https://stackoverflow.com/questions/5189461/passing-an-array-of-strings-to-a-c-function-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!