簡體   English   中英

從指針分配值到變量失敗

[英]assigning value from pointer to variable fails

我在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函數內。 我可以在調試器中看到指針指向的值是正確的。 將這些值分配給局部double變量后,這些變量包含一些垃圾值,而不是正確的值...

我已經嘗試了以下方法,但是沒有一個在工作:

cx = *up->ux;

要么

cx = *(up->ux);

要么

cx = up->ux[0];

我想念什么?

預先感謝您的任何幫助...

該代碼編譯沒有任何問題。 問題出在point3D_Compute函數內。 我可以在調試器中看到指針指向的值是正確的。 將這些值分配給局部double變量后,這些變量包含一些垃圾值,而不是正確的值...

我已經嘗試了以下方法,但是沒有一個在工作:

cx = *up->ux;

要么

cx = *(up->ux);

要么

cx = up->ux[0];

我想念什么?

預先感謝您的任何幫助...

嘗試*(up)->ux; 這是up指針持有的值,並從該值中選擇ux字段

即使我不明白為什么它不能按標准方式工作,我也找到了可行的解決方案:

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...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM