C语言 通过引用将字符串数组传递给 C 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5189461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing an array of strings to a C function by reference
提问by user246392
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:
这是否代表 513 个字符串?这是我初始化第一个元素的方式:
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?
现在,我需要通过引用将“参数”传递给函数,以便函数可以向其添加更多字符串。函数头看起来如何,我将如何在函数内部使用这个变量?
回答by Dietrich Epp
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:
在 C 中,当您将数组传递给函数时,编译器会将数组转换为指针。(数组“衰减”为指针。)上面的“func”完全等同于:
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:
您可能想阅读 C 中指针和数组的工作原理。与大多数语言不同,在 C 中,指针(引用)和数组在许多方面的处理方式相似。数组有时会衰减为指针,但仅在非常特定的情况下。例如,这不起作用:
void func(char **p);
void other_func(void)
{
char arr[5][3];
func(arr); // does not work!
}
回答by peoro
char* parameters[513];is an array of 513 pointers to char. It's equivalent to char *(parameters[513]).
char* parameters[513];是一个包含 513 个指针的数组char。它相当于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:
指向该事物的指针的类型char *(*parameters)[513](相当于char *((*parameters)[513])),因此您的函数可能如下所示:
void f( char *(*parameters)[513] );
Or, if you want a C++ reference:
或者,如果您想要 C++ 参考:
void f( char *(¶meters)[513] );

