我已经使用 typedef struct
定义了一个结构然后在函数中创建一个指针。我将此指针传递给第二个函数以将值分配给结构元素。
typedef struct
{
double velocity; // there are more variables than this but its the
// same for each variable so only showing it for one.
}Variables;
void information(Variables **constants);
int main()
{
double k;
Variables *Constants=NULL; // the structure variable
information(&Constants); // passed into the 'filling' function
k=Constants->velocity;
printf("Velocity %lf\n",k); //this displays correctly
printf("Velocity %lf\n",Constants->velocity); // this does not display correctly
return;
}
void information(Variables **Constants)
{
Variables *consts,constants; //creates the struct to be filled
consts=&constants;
constants.velocity=30.2;
*Constants=consts; //assigns the pointer to the pointer passed into the function
return;
}
在这里你可以看到我显示了两次速度。第一次我将指针中的值分配给变量,一切都运行良好。如果我尝试使用 printf("Velocity %lf\n",Constants->velocity);
行直接显示该代码给出一个随机数。
我已使用 .dot
显示数字之前的结构格式,但从未通过指针,所以我不明白可能出了什么问题。
最佳答案
因为促销。它与 struct 或指针无关。
插图:
double k;
int i;
i = 123456;
k = i; // here i is promoted to double before the assignment
// takes place, now k contains 123456.0000
printf("Velocity %lf\n", k); // this displays correctly
// because k is a double and %lf is the format
// specifier for double
printf("Velocity %lf\n", i); // this does not display correctly
// because i is an int and if you use the %lf
// format specifier with an int, then you will
// get undefined behaviour hence the garbage
// that is printed
printf("Velocity %lf\n", (double)i);
// this does not display correctly because the cast
// converts the int to a double
关于c - 从结构指针打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35802373/