将一个bool /int数组传递给函数,该函数应该对其进行修改

Passing an array of bools/ints to function which should alter it

本文关键字:函数 修改 一个 bool 数组 int      更新时间:2023-10-16

我在一个函数中定义了一个bool数组(也有int数组的版本-不确定当我只想存储1和0时哪个更好)。如何将它传递给另一个函数这个函数返回的是数组之外的东西?我正在参考,但我得到错误。

bool functionWithAltering (bool &(Byte[]), int...){
    ...
}
bool functionWhereSetting (.....) {
    bool Byte[8];
    ....
    if (!functionWithAltering(Byte, ...))
         return 0;
    bool Byte[16];
    ....
    if (!functionWithAltering(Byte, ...))
         return 0;
    ...
}

我得到的错误是:

error: declaration of ‘byte’ as array of references
error: expected ‘)’ before ‘,’ token
error: expected unqualified-id before ‘int’

非常感谢您的建议!

像这样声明functionWithAltering:

bool functionWithAltering (bool Byte[], int...) {
    ...
}
函数实参中的

数组总是衰变成指向第一个元素的指针——它们从不通过copy传递,因此您不必担心可能低效的复制。这也意味着在functionWithAltering()中对Byte[i]的任何修改都会被调用者看到。

对于布尔值数组的使用:如果你只想存储0或1,这是一个完全有效和明智的选择。

数组引用的正确声明如下

bool functionWithAltering( bool ( &Byte )[8], int...){
    ...
}

也可以使用两个形参:指向数组的指针和数组的大小

bool functionWithAltering( bool Byte[], size_t size,  int...){
    ...
}