有人可以帮助这个程序是不正确的? [英] Can someone help what is incorrect in this program?

查看:100
本文介绍了有人可以帮助这个程序是不正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void func(int* ptr)
{
    ptr =  new int;
}

int main() 
{
    int* ptr;
    func(ptr);
    *ptr = 2;
}

这是我面对的面试问题之一。在main()中,它声明一个int指针,在另一个函数中分配内存,并尝试在main()本身中使用。

This was one of the interview questions I faced. in main (), it is declaring an int pointer, allocating it memory in another function and trying to utilise in the main() itself. It is erroneous in some way I think, but how else should this work, any idea?

推荐答案

这是一个错误的方式, ptr 通过值传递给 funcn ,所以参数 ptr code> main 中的code> ptr 。对 func ptr 的任何更改不会修改 main ptr ,因此不会为<$​​ c $ c> main 中的指针 ptr c $ c>。未初始化指针的分配

ptr is passed to funcn by value so the parameter ptr only gets the copy of ptr in main. Any changes to func's ptr would not modify main's ptr and hence memory is not allocated for the pointer ptr in main. The assignment to uninitialized pointer

*ptr = 2;    

调用未定义的行为

invokes undefined behavior.

可能的解决方案:

使用指针

void func(int** ptr)
{
    *ptr =  new int;
}

int main() 
{
    int* ptr;
    func(&ptr);
    *ptr = 2;
}  

从函数返回指针

int* func(int* ptr)
{
    ptr =  new int;
}

int main() 
{
    int* ptr;
    ptr = func(ptr);
    *ptr = 2;
}  

使用参考

void func(int&* ptr)
{
    ptr =  new int;
}

int main() 
{
    int* ptr;
    func(ptr);
    *ptr = 2;
}

这篇关于有人可以帮助这个程序是不正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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