<分区>
我设法将出现问题的代码浓缩为:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct
{
double height;
double hello;
}Variables;
void information(Variables **Constants);
int main()
{
Variables *Constants=NULL;
information(&Constants); //Assigns values to the structure pointer
printf("Height %lf \n",Constants->height); //These print correctly only
printf("hello %lf \n",Constants->hello); //intermittently
return(0);
}
void information(Variables **Constants) //Assigns values structure pointer
{
Variables *consts,constants;
constants.height=10;
constants.hello=20;
consts=&constants;
*Constants=consts;
printf("Height %lf \n",constants.height); //These always print correctly
printf("hello %lf \n",constants.hello);
return;
}
据我了解,这段代码应该在 main 中创建一个结构指针,*Constants
。然后使用 information(&Constants)
将该指针传递到函数中。在 information()
中创建了另一个指针并为其分配了一个结构变量。然后填充变量并将指针分配给 *Constants
,然后允许将整个结构传递回 main()
。
如果我在 information()
中打印结构,则值是正确的。但是,如果我在 main()
中打印值,这些值有时是正确的,或者它们会打印随机数。如果您能帮助理解这一点,我们将不胜感激。