[英]regarding pointers in c++
i have a function like this 我有这样的功能
void some_func(some_type *var)
{
// do something a get a var2 of type some_type*
var = var2;
}
and in main i have 我主要是
some_type *var;
some_func(var);
print_var(var);
but i get a segmentation fault when i run the program. 但是我在运行程序时遇到了分段错误。 debugging shows that
print_var
is the problem, as if var
has no value. 调试显示出
print_var
是问题,就像var
没有值一样。 var2
is initialized using new some_type
, so i think i don't need to do this for var
. var2
使用new some_type
初始化,所以我认为我不需要为var
执行此操作。
but when i do var = new some_type
in main, and i manually clone (copy each data of var2
to var
) in some_func
, i don't get the error. 但是当我在main中执行
var = new some_type
并在some_func
手动克隆(将var2
每个数据复制到var
)时,我没有收到错误。
where is my problem? 我的问题在哪里? i am not really used to pointer and memory allocation things, but i think both ways should work.
我不是很习惯于指针和内存分配的事情,但是我认为这两种方法都应该起作用。 am i wrong?
我错了吗?
maybe the main question is when i allocate a pointer using new
in a function, and then hold its address in an argument of pointer, does the memory get deallocated when the function finishes? 可能的主要问题是,当我在函数中使用
new
分配一个指针,然后将其地址保存在指针的参数中时,函数完成后是否会释放内存?
You need to change your definition to: 您需要将定义更改为:
void some_func(some_type*& var)
{
// var will also be changed on the caller side
var = var2;
}
Notice that it passes a reference to a pointer so the value of the pointer can be updated by the callee. 注意,它传递了对指针的引用,因此被调用者可以更新指针的值。
Your someType *var
in main()
is local to main and the *var
in the function is local to that function. 您在
main()
someType *var
是main()
局部变量,而函数中的*var
是该函数的局部变量。
So, the var
in function is pointing to var2
but not the one which is present in main. 因此,函数中的
var
指向var2
而不是main中存在的那个。
You are passing var
by value. 您正在按值传递
var
。 This means that a copy of var
is made on the stack, separate from the var
in main. 这意味着在堆栈上制作了一个
var
副本,与main中的var
分开。 This copy is then initialized with var2
. 然后使用
var2
初始化此副本。 But, when some_func
exits, the stack is popped, and the copy is lost. 但是,当
some_func
退出时,将弹出堆栈,并且副本将丢失。 The var
declared in main is unchanged. main中声明的
var
保持不变。
To fix this, one possible way would be for some_func
to return a pointer value, which you can then assign to var
. 要解决此问题,一种可能的方法是让
some_func
返回一个指针值,然后可以将其分配给var
。
Alternately, change your declaration of some_func
to 或者,将您的
some_func
声明更改为
void some_func(some_type *& var)
This passes var
by reference, meaning that, for all you are concerned, the var
in some_func
is the same as the var
in main
. 这通过
var
参考,这意味着,所有你关心的var
在some_func
是一样的var
在main
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.