c++ - 不同的传参,不同的输出

标签 c++ memory-management parameter-passing

如果我们有以下代码,当我们调用函数f 时,变量b 的内存不会被占用。但是,如果函数 f 的原型(prototype)是 void f(int* &a),那么内存就会被分配。这怎么可能?

#include <iostream>

using namespace std;


void f(int* a)
{
    a = new int[10];
    a[0] = 55;
}


int main()
{
    int *b;
    f(b);
    return 0;
}

编辑: 好吧,我明白了主要想法,但为什么仍然可行呢?

void f(int a[])
{
     a[0] = 5;
}

int b[] = {1,2,3,4,5};
f(b);

//The value of b[0] will be 5 after the end of function call

最佳答案

您正在按值传递指针,因此 f 有它自己的拷贝。指针 af 的本地指针,因此调用者无法访问它(并且分配的内存已泄漏,顺便说一句)。

当您通过引用传递指针时,a 在语义上与传递的指针相同。所以调用者传递的指针指向函数中分配的内存。

关于c++ - 不同的传参,不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127422/

相关文章:

c++ - 为什么 floor 不返回整数?

Linux 堆栈驻留内存在堆栈展开后未回收

Java 递归传值

C 自由函数(不使用 malloc)

c - realloc 是否会改变其参数

c - 与 C 中的 main() 函数不同

c++ - 哪种 "return"方法更适用于C++/C++11中的大数据?

c++ - 按位 & 运算符返回 255

c++ - 错误 : 'class' does not name a type C++

c++ - 为什么这个 "optimization"会减慢我的程序?