在两个函数之间发送数组C++

Sending an array between two functions C++

本文关键字:之间 数组 C++ 函数 两个      更新时间:2023-10-16

我正在尝试在C++的两个函数之间发送一个包含 15 个整数的数组。第一个功能允许用户输入出租车 ID,第二个函数允许用户从数组中删除出租车 ID。但是,我在函数之间发送数组时遇到问题。

void startShift ()
{
    int array [15]; //array of 15 declared 
    for (int i = 0; i < 15; i++)
    {
        cout << "Please enter the taxis ID: ";
        cin >> array[i]; //user enters taxi IDs
        if (array[i] == 0)
            break;
    }
    cout << "Enter 0 to return to main menu: ";
    cin >> goBack;
    cout << "n";
    if (goBack == 0)
        update();
}
void endShift ()
{
    //need the array to be sent to here
    cout << "Enter 0 to return to main menu: ";
    cin >> goBack;
    cout << "n";
    if (goBack == 0)
        update();
}

任何帮助都是非常有价值的。非常感谢。

由于数组是在堆栈上创建的,因此您只需将指向第一个元素的指针作为 int* 传递

void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}
int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}

由于数组是在堆栈上创建的,因此一旦在其中创建数组的例程退出,它将不再存在。

在这些函数之外声明数组,并通过引用将其传递给它们。

void startShift(int (&shifts)[15]) {
 // ...
}
void endShift(int (&shifts)[15]) {
 // ...
}
int main() {
  int array[15];
  startShift(array);
  endShift(array);
}

这并不完全是漂亮的语法或所有常见。更可能的编写方法是传递指向数组及其长度的指针。

void startShift(int* shifts, size_t len) {
  // work with the pointer
}
int main() {
  int array[15];
  startShift(array, 15);
}

惯用C++会完全不同,并使用迭代器从容器中抽象出来,但我想这超出了这里的范围。无论如何,示例:

template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
  // work with the iterators
}
int main() {
  int array[15];
  startShift(array, array + 15);
}

您也不会使用原始数组,但std::array .

startShift() 函数中使用本地数组是行不通的。您最好执行以下一项或多项操作:

  1. 在调用startShift()endShift()的函数中使用数组,并将数组传递给这些函数,例如:

    void startShift(int* array) { ... }
    void endShift(int* array) { ... }
    int main() {
        int arrray[15];
        // ...
        startShift(array);
        // ...
        endShift(array);
        // ...
    }
    
  2. 首先不要使用内置数组:改用std::vector<int>:该类会自动维护数组的当前大小。您也可以从函数中返回它,尽管您可能仍然最好将对象传递给函数。

void endShift (int* arr)
{
    arr[0] = 5;
}