它是通过指针传递的吗? [英] Is it passing by pointer?

查看:51
本文介绍了它是通过指针传递的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void func(char* buf) { buf++;}

我应该称它为通过指针传递还是仅通过值传递(值是指针类型)?在这种情况下,传入的原始指针会被改变吗?

Should I call it passing by pointer or just passing by value(with the value being pointer type)? Would the original pointer passed in be altered in this case?

推荐答案

这是按值传递.

void func( char * b )
{
    b = new char[4];
}

int main()
{
    char* buf = 0;
    func( buf );
    delete buf;
    return 0;
}

调用func后buf仍为0,新的内存会泄漏.

buf will still be 0 after the call to func and the newed memory will leak.

当您按值传递指针时,您可以更改指针指向的内容,而不是指针本身.

When you pass a pointer by value you can alter what the pointer points to not the pointer itself.

做上述事情的正确方法是

The right way to do the above stuff would be

备选方案 1

void func( char *& b )
{
    b = new char[4];
}

int main()
{
    char* buf = 0;
    func( buf );
    delete buf;
    return 0;
}

请注意,指针是通过引用而不是值传递的.

Notice the pointer is passed by reference and not value.

备选方案 2

另一种选择是将指针传递给像

Another alternative is to pass a pointer to a pointer like

void func( char ** b )
{
    *b = new char[4];
}

int main()
{
    char* buf = 0;
    func( &buf );
    delete buf;
    return 0;
}

请注意,我绝不提倡像上面那样使用裸指针和手动内存管理,而只是说明传递指针.C++ 方法是使用 std::stringstd::vector 代替.

Please note I am not in any way advocating the use of naked pointers and manual memory management like above but merely illustrating passing pointer. The C++ way would be to use a std::string or std::vector<char> instead.

这篇关于它是通过指针传递的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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