gpt4 book ai didi

c - 从指针赋值给变量失败

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:23 27 4
gpt4 key购买 nike

我在 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 字段

关于c - 从指针赋值给变量失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22666599/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com