0xC0000005:访问冲突写入位置0xcccccccc

时间:2012-10-01 20:56:50

标签: c++ pointers pass-by-reference

当我调用我的calculatePlaneEQ函数时,当我分配值时,它会抛出一个访问冲突...我的指针生锈了但是看起来这应该有用了!

float *planeCoefA, *planeCoefB, *planeCoefC, *planeCoefD = NULL;

来电:

calculatePlaneEQ (<...>, &planeCoefA, &planeCoefB, &planeCoefC, &planeCoefD);

DEF:

void calculatePlaneEQ (<...>, float ** myXnorm, float ** myYnorm, float ** myZnorm, float** myD)
{
    float  xNorm = 1.3;
    float  yNorm = 1.4;
    float  zNorm = 1.5;
    float eqD = 1.6; 

    *(*myXnorm) = xNorm;
    *(*myYnorm) = yNorm;
    *(*myZnorm) = zNorm;
    *(*myD) = eqD;  
}

4 个答案:

答案 0 :(得分:8)

应该是:

float planeCoefA, planeCoefB, planeCoefC, planeCoefD;

CALL:

calculatePlaneEQ (<...>, &planeCoefA, &planeCoefB, &planeCoefC, &planeCoefD);

DEF:

void calculatePlaneEQ (<...>, float * myXnorm, float * myYnorm, float * myZnorm, float * myD)
{

    float  xNorm = 1.3;
    float  yNorm = 1.4;
    float  zNorm = 1.5;
    float eqD = 1.6; 

    *myXnorm = xNorm;
    *myYnorm = yNorm;
    *myZnorm = zNorm;
    *myD = eqD;
}

更好的是,使用引用而不是指针:

CALL:

calculatePlaneEQ (<...>, planeCoefA, planeCoefB, planeCoefC, planeCoefD);

DEF:

void calculatePlaneEQ (<...>, float &myXnorm, float &myYnorm, float &myZnorm, float &myD)
{

    float  xNorm = 1.3;
    float  yNorm = 1.4;
    float  zNorm = 1.5;
    float eqD = 1.6; 

    myXnorm = xNorm;
    myYnorm = yNorm;
    myZnorm = zNorm;
    myD = eqD;
}

这是比C语言使用指针更惯用的C ++,并且不易出错。

答案 1 :(得分:1)

float *planeCoefA, *planeCoefB, *planeCoefC, *planeCoefD = NULL;

您尚未初始化任何指针。 planeCoefAplaneCoefBplaneCoefC将具有随机值。仅为planeCoefD分配了NULL,但这对于写入任何一个都无效。

但是,您仍然只是为这些内存位置分配值。这是未定义的行为。指针是变量,它们的值是内存地址。但是,它们不会自动指向有效内存;他们需要初始化。

float planeCoefA = 0, planeCoefB = 0, planeCoefC = 0, planeCoefD = 0;

// ...

void calculatePlaneEQ (<...>, float *myXnorm, float *myYnorm, float *myZnorm, float* myD)

添加另一个间接级别(即float** v float*)的唯一原因是,如果您需要修改参数,以便可以通过调用者(因为,记住;你通过值传递这些参数)。您只需要写入指针引用的内存位置,因此单个指针就足够了。

答案 2 :(得分:1)

似乎你太过分了一层间接。

float planeCoefA, planeCoefB, planeCoefC, planeCoefD;

呼叫

calculatePlaneEQ (<...>, &planeCoefA, &planeCoefB, &planeCoefC, &planeCoefD);

void calculatePlaneEQ (<...>, float * myXnorm, float * myYnorm, float * myZnorm, float* myD)
{
 ...
  *myXnorm = 12.1f;
 ...

答案 3 :(得分:0)

您可以随时使用真正的花车和参考资料,让自己和他人更简单。

float planeCoefA = 0.0;
float planeCoefB = 0.0;
float planeCoefC = 0.0;
float planeCoefD = 0.0;

CALL:     calculatePlaneEQ(&lt; ...&gt;,planeCoefA,planeCoefB,planeCoefC,planeCoefD);

DEF:

void calculatePlaneEQ (<...>, float & myXnorm, float & myYnorm, float & myZnorm, float & myD)
{

    myXNorm = 1.3;
    myYNorm = 1.4;
    myZNorm = 1.5;
    myD = 1.6; 

}

如果你更喜欢使用指针,那么你可以在函数签名中使用浮点指针:

void calculatePlaneEQ (<...>, float * myXnorm, float * myYnorm, float * myZnorm, float * myD)

在这种情况下,您将在函数正文中的每个变量名前面加一个星号:

*myXNorm = 1.3;

然而,您将冒被传递无效指针的风险。