指针困扰 C++

Pointer troubles C++

我得到了以下代码,它编译完美,但在执行程序时,它只是崩溃并关闭。我不知道为什么。

main{
...
  MLdouble *u = NULL;
  _intersect(...,u,...); //u as MLdouble* type
... 
}

CurvatureCalc::_intersect(... MLdouble *u)
{
...
MLdouble test = 123.21
*u = test; //<---line where it crashes
}

我做错了什么?可能是我只是监督的一些简单的事情。没有其他地方使用你。我已经尝试过的是不同的变体,例如使用 u = &test,这显然也不起作用。提前致谢。

既然你是用 C++ 编程,你真正应该做的是通过引用传递参数:

CurvatureCalc::_intersect(... MLdouble &u, ...)  // Note use of & instead of *
{
    ...
    u = ...;  // No dereference
    ...
}

并调用 "normal"

MLdouble u;  // Not a pointer
_intersect(..., u, ...);

使用指针是模拟通过引用传递的旧C方式,它不是通过传递一个指针变量,而是传递一个指针to 变量。像这样:

MLdouble u;  // Not a pointer
_intersect(..., &u, ...);  // Note use of address-of operator & here

您现在所做的是取消引用空指针,这是不允许的。

I got the following code, which compiles perfectly

它编译是因为它在语法上是正确的。语法正确并不意味着该程序完全正确

but by executing the program, it just crashs

您的代码中有未定义的行为。

What am I doing wrong?

您将指针初始化为空:

MLdouble *u = NULL;

您将空指针传递给函数:

_intersect(...,u,...); //u as MLdouble* type

您取消引用空指针:

*u = test; //<---line where it crashes

取消引用空指针(或任何未指向有效对象的指针)具有未定义的行为。

解决方案是使用指向有效对象的指针。或者,如果您可以修改 _intersect,则将参数更改为引用,这样就不会意外传递空值。

提供更多代码但初看;

MLdouble *u = NULL; // u is nullptr,

*u = test; /* you pass pointer which doesnt point to any address yet
and write - unexpected behavior, even if you pass address of local variable to u aka u = &test
test will get destroyed when, 
and you pointer will point to "garbage"*/

所以你必须使用新运算符然后删除它或使用智能指针

MLdouble *u = new MLdouble(...);/// or auto u = new MLdouble(...);
delete u;
u = nullptr;