通过引用将字符串数组传递给C函数 [英] Passing an array of strings to a C function by reference

查看:199
本文介绍了通过引用将字符串数组传递给C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难通过引用将字符串数组传递给函数.

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

  char* parameters[513]; 

这代表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?

推荐答案

您已经掌握了它.

#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;
}

在C语言中,当您将数组传递给函数时,编译器会将数组转换为指针. (数组衰减"到一个指针中.)上面的"func"完全等同于:

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.

您可能想了解C语言中指针和数组的工作方式.与大多数语言不同,在C语言中,指针(引用)和数组在很多方面都得到类似的处理.数组有时会衰减为指针,但只能在非常特殊的情况下使用.例如,这不起作用:

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

这篇关于通过引用将字符串数组传递给C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆