如何通过引用C ++中的函数传递数组?

时间:2010-11-23 23:02:40

标签: c++ arrays

我有以下程序,其中两个变量将通过引用传递给函数,在返回main()之前,它们的值将根据外部因素确定,以便其他函数可以使用它们。我试图传递的第一个变量是int,这很好,但另一个变量是一个字符串数组,这会给我带来一些问题。

我已经对此做了足够的研究,知道你不能有一个数组或引用(虽然我还没弄清楚为什么),我想知道是否有人可以帮我弄清楚如何做到这一点?我尝试过的各种方法都产生了segmentation faults

NB :下面的代码是按值传递数组的,因为我只是不知道要为它写什么。

更新:我需要在课程中使用数组。其他一些数据结构,例如已建议的vector,会很棒,但我必须使用特定的结构。

void initialise_existing_devices(int& no_of_existing_devices, string existing_devices[100]);

int main()
{
    int no_of_existing_devices = 0;
    string existing_devices[100];

    initialise_existing_devices(no_of_existing_devices, existing_devices[100]);
}

void initialise_existing_devices(int& no_of_existing_devices, string existing_devices[100])
{
    string line;
    ifstream DeviceList;
    DeviceList.open("devices/device_list");
    while (true)
    {
        getline(DeviceList, line, '\n');
        if (DeviceList.eof())
        {
            break;
        }
        ++ no_of_existing_devices;
    }
    DeviceList.close();

    DeviceList.open("devices/device_list");
    for (int i = 0; i < no_of_existing_devices; i ++)
    {
        getline(DeviceList, line, '\n');
        existing_devices[i] = line;
    }
}

6 个答案:

答案 0 :(得分:5)

对数组的引用如下所示:

void f(std::string (&a)[N]) { }

其中a是参数的名称,N是数组中元素的数量。


但是,通常在C ++中你没有通过引用传递数组(你可以;它只是不常见)。其他选项包括:

  • 将指针传递给数组的初始元素;在这种情况下,请考虑将数组的大小作为第二个参数传递给函数。

  • 使用std::vector<std::string>std::array<std::string, N>代替并通过引用传递它(您还可以在Boost中找到array伪容器;除此之外,请考虑编写自己的容器如果你看一下Boost源代码,那就非常简单直接了。)

  • 将一对迭代器(开始和结束)传递给函数,并使用它们来操作范围。

最后一个选项是最惯用的C ++方法;它也是最通用的,因为你可以使用任何类型的容器,包括你自己编写的数组,标准库容器或容器。


由于您实际上是尝试将参数用作“out”参数,因此最好只返回包含结果的std::vector<string>std::array<string, 100>;这更清洁。

答案 1 :(得分:1)

这条线没有按照你的预期行事:

initialise_existing_devices(no_of_existing_devices, existing_devices[100])

提示:数组索引,100 ......

我建议您使用std::vector<std::string>而不是数组,并通过引用传递它。

编辑:好的,鉴于更新:

你可以使用struct吗?如果是这样,您可以将数组包装在struct

struct string_array
{
  string data[100];
};

然后在main中定义一个这样的实例,并通过引用传递它?我相信你可以填写详细信息.. :)

答案 2 :(得分:0)

对于堆托管数组应使用std::vector<T>,对基于堆栈的数组使用boost:: / std::array<T, N>。这些对象将保持自己的大小。

答案 3 :(得分:0)

对于实际参数,只使用数组名称,它代表数组的地址:

initialise_existing_devices(no_of_existing_devices, existing_devices);

对于参数,使用它作为指向数组的常量指针:

void initialise_existing_devices(int& no_of_existing_devices, string existing_devices[])

也就是说,使用std :: vector作为返回类型或引用参数可以避免在调用之前猜测设备的数量。

答案 4 :(得分:0)

这是C ++与C共有的东西之一。数组不是通过值传递的。他们被降级为指向他们的第一个元素的指针。函数参数中的数组语法基本上只是一个注释。您可以通过在函数调用中执行sizeof(existing_devices)来判断。所以问题的答案就是你已经在做了。

答案 5 :(得分:0)

您可以使用模板,如下所示:

template <size_t size> 
initialise_existing_devices(int& no_of_existing_devices, string (&existing_devices)[size])
{
}

或者你可以这样做:

typedef string hundred_strings[100];

initialise_existing_devices(int& no_of_existing_devices, hundred_strings &existing_devices)
{
}
相关问题