Cで(ネストされた)構造を前方参照しようとしています.
つまり、構造体があり、その中で後で宣言される別の構造体を参照しています。
ネストされた構造をポインターとして宣言し、値で初期化すると、機能します。
次のコードが機能します。
#include <stdio.h>
struct computer{
double cost;
int year;
char cpu_type[16];
struct cpu_speed *sp; //this is the question (1)
};
struct cpu_speed{
int num;
char type[16];
};
typedef struct computer SC;
typedef struct cpu_speed SS;
void DataR(SC *s);
void DataP(SC *s);
int main(){
// this is question (2)
SS speed = {4,"giga"};
SC model[2] = {
{ 0,1990, "intel", &speed},
{ 0,1990, "intel", &speed}
};
int i;
for(i=0;i<2;i++) {
printf("computer no. %d \n", i+1);
DataR(&model[i]);
}
printf("here's what you entered: \n");
for(i=0;i<2;i++) {
printf("computer no. %d \n", i+1);
DataP(&model[i]);
}
return 0;
}
void DataR(SC *s){
printf("the cost of your computer: ");
scanf("%lf", &s->cost);
printf("the year of your computer: ");
scanf("%d", &s->year);
printf("the type of cpu inside your computer: ");
scanf("%s", s->cpu_type);
printf("the speed of the cpu: ");
scanf("%d %s", &(s->sp->num), s->sp->type);
}
void DataP(SC *s){
printf("the cost: %.2lf\n",s->cost);
printf("the year: %d\n",s->year);
printf("the cpu type: %s\n",s->cpu_type);
printf("the cpu speed: %d %s\n",s->sp->num, s->sp->type);
}
親 (?) 構造体の前にネストされた構造体 (すなわちstruct cpu_speed{...};
) を宣言すると、ポインターを使用する必要がなくなり、初期化も必要なくなります。
意味:
struct cpu_speed speed;
(1)の代わりに使えますstruct cpu_speed *sp;
。(2) 構造体変数に初期値を与える必要がない。
もう一度質問します-前方参照構造で-(1)ポインターで宣言する必要がありますか? (2)値を初期化する必要がありますか?