从指针到变量赋值失败

时间:2014-03-26 15:59:25

标签: c pointers struct

我在C(!!!而不是C ++ !!!)代码中有以下场景:

#include <stdlib.h>

struct point
{
    double *x, *y;
};

void point_Construct(struct point *p)
{
    p->x = (double*)malloc(sizeof(double));
    p->y = (double*)malloc(sizeof(double));
}

struct point3D
{
    double *ux, *uy, *uz;
};

void point3D_Construct(struct point3D *uP, double *x, double *y, double *z)
{
    uP->ux = x; //assigning pointers to pointers
    uP->uy = y;
    uP->uz = z;
}

void point3D_Compute(struct point3D *uP)
{
    double cx, cy, cz;

    //the following 3 lines do not work...
    //i.e.,  *uP->ux contains the right value but after assigning this value
    //to the cx variable, the cx holds some unreasonable value...
    cx = *uP->ux; //assigning values to which the pointers points to local variables
    cy = *uP->uy;
    cz = *uP->uz;

    cz = cx + cy; //using values

    //... other code...
}

static struct point  instPoint;  //create structures
static struct point3D instPoint3D;

static double mx, my, mz; //declare global variables

int main(void)
{

    mx = 1.0; //assigning values to static variables
    my = .0;
    mz = 24.5;

    point_Construct(&instPoint); //alloc memory for struct point

    //assigning values to the place in memory where pointers of the point struct point
    *instPoint.x = mx;
    *instPoint.y = my;

    //inicialize pointers of the point3D struct to memory addresses 
    //pointed by the pointers of the point struct and
    //to the address of the mz static global variable
    point3D_Construct(&instPoint3D, instPoint.x, instPoint.y, &mz);


    point3D_Compute(&instPoint3D); //using all the values

    //...other code...
}

代码编译没有任何问题。 问题在point3D_Compute函数内。我可以在调试器中看到指针指向的值是正确的。 将此值分配给本地双变量后,这些变量包含一些垃圾值而不是正确的值......

我已经尝试过以下方法,但其中没有一个方法正在运行:

cx = *up->ux;

cx = *(up->ux);

cx = up->ux[0];

我错过了什么?

提前感谢您的帮助......

代码编译没有任何问题。 问题在point3D_Compute函数内。我可以在调试器中看到指针指向的值是正确的。 将此值分配给本地双变量后,这些变量包含一些垃圾值而不是正确的值......

我已经尝试过以下方法,但其中没有一个方法正在运行:

cx = *up->ux;

cx = *(up->ux);

cx = up->ux[0];

我错过了什么?

提前感谢您的帮助......

2 个答案:

答案 0 :(得分:0)

尝试*(up)->ux;这是up指针所持有的值,并从该值中选择ux字段

答案 1 :(得分:0)

即使我不明白为什么它不按标准方式工作,我找到了可行的解决方案:

void point3D_Compute(struct point3D *uP)
{
    double cx, cy, cz;
    double *pCx, *pCy;

    pCx = &cx;
    pCy = &cy;    

    pCx = uP->ux; 
    pCy = uP->uy;

    cz = cx + cy; //it is OK now...

    //... other code...
}