将数组传递给函数c++

Passing arrays to functions c++?

本文关键字:函数 c++ 数组      更新时间:2023-10-16

我想从用户输入中读取一些数字,然后在每行显示5。我的代码是这样的:

#include <iostream>
using namespace std;
const int INPUT_SIZE = 7;
void printValues(int *b) {
    int counter = 0;
    while (counter < INPUT_SIZE) {
        cout << *(b+counter) << " ";
        if ((counter + 1) % 5 == 0 && counter>0) {
            cout << endl;
        }
        counter++;
    }
    cout << endl;
    system("pause");
}
int * readValues() {
    int b[INPUT_SIZE];
    for (int i = 0; i < INPUT_SIZE; i++) {
        cout << "Enter element on position: " << i << ": ";
        cin >> b[i];
    }
    return b;
}
int main() {
    int* b;
    b = readValues();
    printValues(b);
    return 0;
}

然而,当我试图打印它们时,我会得到一些奇怪的数字,我认为这些数字是内存位置。如何打印数组,以及如何编写返回数组的函数?我对指针没有什么经验,因为到目前为止我只使用Java进行编码。非常感谢您的帮助。

您的数组b是函数readValues内的局部变量。

readValues退出时,阵列将被销毁。

一旦函数返回,从readValues返回的指针就会失效。尝试使用它(例如将其传递给printValues)是不正确的(形式上,它会导致未定义的行为)。

main中的指针变量的名称b与将readValues中的数组b的名称相同,可能会造成一些混乱。它们是完全独立的变量。

如果你想在两个函数中使用同一个数组,你需要确保它位于一个范围内,该范围确保它在你需要的时间内有效。这可以通过使它成为main中的局部变量来实现。