【发布时间】:2019-06-14 22:26:56
【问题描述】:
我是 C 的新手,我的代码有一个奇怪的问题。
我正在尝试创建一个 struct 数组作为另一个 struct 数组的一部分。
当printf 函数的数量不同时,我得到不同的输出。我有两种情况,一种是正确的,另一种是错误的。
我不明白为什么一个额外的printf 的简单调用会改变结果。
这是我的代码,结果不正确,这里我得到“x velocity=-nan”
#include<stdlib.h>
#include<stdio.h>
struct vect3d1
{
double *x,*y,*z;
};
struct block
{
int ibl;
struct vect3d1 *velocity;
};
void create_time(struct block *blocks,int Nsteps,int nb);
int main()
{
struct block *blocks;
int nb,i,t,Nsteps;
Nsteps=30;
nb=3;
blocks=calloc(nb, sizeof(struct block));
for (i=0;i<nb;i++){
for(t=0;t<Nsteps;t++){
blocks[i].velocity=(struct vect3d1 *)malloc(Nsteps*sizeof(struct vect3d1));
blocks[i].velocity[t].x=NULL;
blocks[i].velocity[t].y=NULL;
blocks[i].velocity[t].z=NULL;
}
}
create_time(blocks,Nsteps,nb);
free(blocks);
}
void create_time(struct block *blocks,int Nsteps,int nb){
int i,t;
double u;
for (i=0;i<nb;i++){
for(t=0;t<Nsteps;t++){
u=0.5+t;
blocks[i].velocity[t].x=&u;
// printf("u %lf \n",u);
printf("velocity x=%lf \n",blocks[i].velocity[t].x);
}
}
}
你可以注意到函数create_time中的一行被注释了,当它没有被注释时结果是正确的。
只是为了澄清,如果函数create_time是:
void create_time(struct block *blocks,int Nsteps,int nb){
int i,t;
double u;
for (i=0;i<nb;i++){
for(t=0;t<Nsteps;t++){
u=0.5+t;
blocks[i].velocity[t].x=&u;
// printf("u %lf \n",u);
printf("velocity x=%lf \n",blocks[i].velocity[t].x);
}
}
}
我得到:
"velocity x=-nan"
当函数为:
void create_time(struct block *blocks,int Nsteps,int nb){
int i,t;
double u;
for (i=0;i<nb;i++){
for(t=0;t<Nsteps;t++){
u=0.5+t;
blocks[i].velocity[t].x=&u;
printf("u %lf \n",u);
printf("velocity x=%lf \n",blocks[i].velocity[t].x);
}
}
}
我得到:
"u 0.5"
"velocity x=0.5"
...
等等。
我添加该行只是为了验证变量u,然后我意识到添加它会更改printf 的输出。
发生了什么?为什么printf的输出变了?
【问题讨论】:
-
x是一个指针double *x。你需要尊重它。*blocks[i].velocity[t].x);。打开编译器警告并解决每个警告。 -
blocks[i].velocity分配应该在t循环之外。 -
感谢您的建议。
标签: c struct printf malloc nan