1

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)値を初期化する必要がありますか?

4

1 に答える 1

5

構造体は、メモリを整列するためにコンパイラによってのみ使用されます。したがって、構造体メンバーのサイズを知る必要があります。

struct foo {
    struct bar *pointer;
};

この場合、は構造体とsizeof(pointer)は無関係であるbarため、コンパイラはそれ以上のことを知る必要はありません。

barただし、構造体に構造体を追加する場合はfoo、個々のメンバーについて知る必要があります。

struct bar {
    const char *string;
    uint64_t integer;
};

struct foo {
    struct bar sub;
};

コンパイラは何を参照しているのかを知る必要があるため、bar前に構造体を宣言する必要があります。fooそうでなければ、この (違法な) コードの処理方法をどのように知ることができますか?

struct bar {
    struct foo sub;
};

struct foo {
    struct bar sub;
};
于 2016-07-22T10:51:29.707 に答える