简体   繁体   English

当我没有动态声明我的数组时,这个 display() 如何显示数组值

[英]How this display() displays the array values when I haven't declared my array dynamically

From my knowledge after a function is called in c++ its memory is deallocated for another variables.据我所知,在 C++ 中调用一个函数后,它的内存被释放给另一个变量。 If it doesn't allocates to another variable then variable should have allocated memory dynamically.如果它没有分配给另一个变量,那么变量应该动态分配内存。 I'm confused how the function display() displays array values when it isn't allocated memory dynamically.我很困惑函数 display() 在没有动态分配内存时如何显示数组值。

#include<iostream>
using namespace std;
void init_values(int arr[]){
    for(int i=0;i<100;i++){
        arr[i]=i;
    }
}
void display(int arr[]){
    for(int i=0;i<100;i++){
        cout<<arr[i] << " ";
    }
}
int main(){
    int arr[100];
    init_values(arr);
    display(arr);
}

I expected the function displays garbage or will show an error.我预计该功能会显示垃圾或会显示错误。 But it displayed the values correctly.但它正确显示了值。

void init_values(int arr[]){
    for(int i=0;i<100;i++){ // i is created here
        arr[i]=i;
    } // i goes out of scope here
}

No problems here, there's no attempt to use i later.这里没有问题,以后不会尝试使用i

void display(int arr[]){
    for(int i=0;i<100;i++){ // i is created here
        cout<<arr[i] << " ";
    } // i goes out of scope here

Again, no problem.再次,没问题。

int main(){
    int arr[100]; // arr is created here
    init_values(arr);
    display(arr);
} // arr goes out of scope here

When we call init_values and display , arr is still in scope since its lifetime ends at the end of the scope it was created in. So it's still in scope during those function calls.当我们调用init_valuesdisplayarr仍然在作用域内,因为它的生命周期在它被创建的作用域结束时结束。所以在这些函数调用期间它仍然在作用域内。

Now, this would be a problem:现在,这将是一个问题:

int *init_values(void){
    int arr[100];
    for(int i=0;i<100;i++){
        arr[i]=i;
    }
    return arr;
}

Why?为什么? Think about it:想想看:

int *init_values(void){
    int arr[100]; // arr is created here
    for(int i=0;i<100;i++){
        arr[i]=i;
    }
    return arr;
} // arr goes out of scope here

So the caller of init_values would receive a pointer to arr 's contents even though arr does not exist after we exit this function.所以init_values的调用者会收到一个指向arr内容的指针,即使我们退出这个函数后arr不存在。 This function's return value could not be safely used.无法安全地使用此函数的返回值。 Your code doesn't do this.您的代码不会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM