从结构指针打印

时间:2016-03-04 17:29:20

标签: c pointers struct

我使用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格式显示了数字,但从未通过指针显示数字,所以我不明白可能出现的问题。

1 个答案:

答案 0 :(得分:0)

It's because of promotion. It has nothing to do with struct or with pointers.

Illustration:

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