C++返回数组并显示它

C++ returning array and display it

本文关键字:显示 数组 返回 C++      更新时间:2023-10-16

我想问一下,为什么这段代码不起作用。。。

int* funkce(){
    int array[] = {1,2,3,4,5};
    return(array);
  }
int main(){
    int* pp = funkce();
    int* ppk = pp+5;
    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }
    system("PAUSE");
    return(0);
}

此代码显示:

1
16989655
4651388
- // -
253936048

所以小马出了阵。。。但是怎么可能,这个在Main中有数组的代码是可以的呢?

int main(){
    int a[] = {1,2,3,4,5};
    int* pp = a;
    int* ppk = pp+5;
    for (int *i = pp; i!=ppk; i++){
        cout << (*i) << endl;
    }
    system("PAUSE");
    return(0);
}

显示的代码:

1
2
3
4
5

你能解释一下为什么第一个不起作用吗?非常感谢。

您正在返回一个指向临时对象的指针,该指针在函数结束时超出范围。如果你想让一个函数返回一个数组,你需要做以下之一:

std::array<int, 5> func() {
    // stack-allocated
    std::array<int, 5> a = {1, 2, 3, 4, 5};
    return a;
}
std::vector<int> func() {
    // heap-allocated
    std::vector<int> a = {1, 2, 3, 4, 5};
    return a;
}
int* func() {
    // heap-allocated, you have to remember to delete it
    int* a = new int[5]{1, 2, 3, 4, 5};
    return a;
}

等等。有更多的选择,但这应该会给你一个良好的开端。

永远不要返回本地变量。如果是对变量的指针/引用,则返回时会释放/重新使用内存。

使用悬挂引用是未定义的行为,会产生不可预测的后果。

返回一个对象、指向堆分配内存的指针,或保存到调用方提供的缓冲区中。