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

时间:2014-01-04 23:17:09

标签: c++ arrays function

我试图在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();
}

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

4 个答案:

答案 0 :(得分:2)

由于数组已在堆栈上创建,因此您只需将指针传递给第一个元素,就像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);
}

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

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>:该类自动维护数组的当前大小。您也可以从函数返回它,尽管您可能仍然最好将对象传递给函数。

答案 3 :(得分:1)

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