如何使用指针从不同的函数访问局部变量? [英] How to access a local variable from a different function using pointers?

查看:32
本文介绍了如何使用指针从不同的函数访问局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以访问不同函数中的局部变量吗?如果是,怎么办?

May I have any access to a local variable in a different function? If so, how?

void replaceNumberAndPrint(int array[3]) {
    printf("%i
", array[1]);
    printf("%i
", array[1]);
}

int * getArray() {
    int myArray[3] = {4, 65, 23};
    return myArray;
}

int main() {
    replaceNumberAndPrint(getArray());
}

上面这段代码的输出:

65
4202656

我做错了什么?4202656"是什么意思?

What am I doing wrong? What does the "4202656" mean?

我是否必须在 replaceNumberAndPrint() 函数中复制整个数组才能比第一次访问更多?

Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?

推荐答案

myArray 是一个局部变量,因此指针仅在其作用域结束前有效(在这种情况下是包含函数 getArray) 被留下.如果稍后访问它,则会出现未定义的行为.

myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.

实际上,对printf 的调用会覆盖myArray 使用的堆栈部分,然后它包含一些其他数据.

In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.

要修复您的代码,您需要在生存时间足够长的范围内声明数组(在您的示例中为 main 函数)或在堆上分配它.如果你在堆上分配它,你需要手动释放它,或者使用 RAII 在 C++ 中释放它.

To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.

我错过的另一种选择(可能是这里最好的一种,前提是数组不是太大)是将数组包装到结构中,从而使其成为值类型.然后返回它会创建一个副本,该副本在函数返回后仍然存在.请参阅tp1答案a> 有关这方面的详细信息.

One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.

这篇关于如何使用指针从不同的函数访问局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆