简体   繁体   English

关于C ++中的指针

[英]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 *varmain()局部变量,而函数中的*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参考,这意味着,所有你关心的varsome_func是一样的varmain

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM