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

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

问题描述

例如:

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天全站免登陆