将指向局部变量的指针传递给函数:它安全吗? [英] Passing pointer to local variable to function: is it safe?

查看:14
本文介绍了将指向局部变量的指针传递给函数:它安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

void func1(){
    int i = 123;
    func2(&i);
}
void func2(int *a){
    *a = 456;
}

func1调用func2时,一个指向局部变量的指针被传递给func2——指针指向堆栈.这对 C 的规则安全吗?

When func1 calling func2, a pointer to local variable is passed to func2 -- the pointer is pointed to the stack. Is this safe for the rules of C?

谢谢.

推荐答案

i的作用域是func1,它比调用func2.所以绝对安全.

The scope of i is func1 and it outlives the call to func2. So it is perfectly safe.

这篇关于将指向局部变量的指针传递给函数:它安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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