主位高手们,请教一下:
结构体中还可以继续包含结构体。例如
struct data
{float time;
struct setting;
};
问题是:data形结构体里的setting形结构体的个数能不能根据用户的输入而决定???就是在建立结构体data时,能不能根据用户的输入而决定建立的结构体setting的个数????
你的意思这样?
struct data
{float time;
struct setting s1;
struct setting s2;
...
struct setting sn;
};
如果是那样的话就如3楼所说
struct data
{float time;
struct setting *pS;//指向setting类型的指针就可以了
};
到时候你就可以这样使用:
scanf("%d",&n);
struct data d;
d.pS = (struct setting*) malloc(sizeof(struct setting)*n);
你好,这是我按照你说的编的程序,可是怎么输出的时候只有前两个数据是正确的?
#define NULL 0
struct data
{long time;
struct setting *ps;
struct data *next;
};
struct setting
{int money;
float sum;
struct setting *next;
};
main()
{int n,a;
char s;
struct data *d;struct setting *b;
printf("Please input the totol number \n");
scanf("%d",&n);
d=(struct data*)malloc(sizeof(struct data));
d->ps=b=(struct setting*)malloc(sizeof(struct setting)*n);
printf("please tell me wen you bought this jijin\n");
scanf("%ld",&(*d).time);
for(a=1;a<=n;a++)
{
printf("money\n");
scanf("%d",&((*d).ps)->money);
printf("sum\n");
scanf("%d",&((*d).ps)->sum);
if(a!=n)
{
(d->ps)->next=(struct setting*)malloc(sizeof(struct setting)*n);
d->ps=(struct setting*)malloc(sizeof(struct setting)*n);
}
else
d->ps->next=NULL;
}
d->next=NULL;
getch();
d->ps=b;
printf("%ld\n",(*d).time);
do
{
printf("%d\n",((*d).ps)->money);
printf("%d\n",((*d).ps)->sum);
d->ps=(d->ps)->next;
getch();
}while(d->ps!=NULL);
getch();
}