C++ 返回数组并显示它

标签 c++ arrays

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

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

所以 poniter 超出了数组... 但是怎么可能,这个在 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;
}

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

关于C++ 返回数组并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26539374/

相关文章:

c++ - 如何将元组转换为初始值设定项列表

Javascript - 对数组排序时处理 "The"

Javascript 编码测验未加起来

python - 如何增加 numpy int32 数组的维度?

C++ 按值返回 - 里面的指针会发生什么?

c++ - 如何用c++代码调用matlab自定义函数

c++ - C++ 中的迭代器

c++ - 我应该使用什么标志来执行良好的 C++11 风格?

c++ - Ordered ArrayList 的 Insert 方法出错

python - 在另一个数组中查找数组的字符串元素