C前向引用结构-1)必须带有指针?2) 必须初始化吗?
我试图在C中向前引用嵌套结构 这意味着我有一个结构,在其中我引用了另一个稍后声明的结构 如果我将嵌套结构声明为指针,并使用值对其进行初始化,它就会工作 以下代码起作用:C前向引用结构-1)必须带有指针?2) 必须初始化吗?,c,pointers,struct,initialization,forward-reference,C,Pointers,Struct,Initialization,Forward Reference,我试图在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_
#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);
}
如果我声明嵌套结构,即结构cpu_speed{…};在父结构之前,我不需要使用指针,也不需要初始化
意思是:
1我可以使用结构cpu_速度;而不是结构cpu_speed*sp;。
2我不需要为结构变量提供初始化值
我的问题又来了-在前向引用结构-1中,您必须用指针声明它吗?和2您必须初始化值吗?结构仅由编译器用于对齐内存。因此,它需要知道结构成员的大小
struct foo {
struct bar *pointer;
};
在本例中,sizeofpointer与bar结构无关,因此编译器不需要了解更多信息
但是,如果要将bar结构添加到foo结构中,它确实需要了解其各个成员
struct bar {
const char *string;
uint64_t integer;
};
struct foo {
struct bar sub;
};
您需要在foo之前声明bar结构,因为编译器需要知道您所引用的内容。否则,它如何知道如何处理此非法代码:
struct bar {
struct foo sub;
};
struct foo {
struct bar sub;
};
结构仅由编译器用于对齐内存。因此,它需要知道结构成员的大小
struct foo {
struct bar *pointer;
};
在本例中,sizeofpointer与bar结构无关,因此编译器不需要了解更多信息
但是,如果要将bar结构添加到foo结构中,它确实需要了解其各个成员
struct bar {
const char *string;
uint64_t integer;
};
struct foo {
struct bar sub;
};
您需要在foo之前声明bar结构,因为编译器需要知道您所引用的内容。否则,它如何知道如何处理此非法代码:
struct bar {
struct foo sub;
};
struct foo {
struct bar sub;
};
试想:一个递归结构是如何工作的?虽然相关,但这与嵌套无关。试想:递归结构如何工作?虽然相关,但这与nestingok无关,因此基本上您最好不要使用前向引用结构,如果使用,则必须使用指针并初始化它们。对吗?前向引用结构没有错。例如,当您使用它们来保护结构成员不受面向公共API的攻击时,这是非常好的。但是如果你这样做了,那么你总是必须使用指针和malloc来创建一个新的实例,是的。好的,所以基本上你最好不要使用前向引用结构,如果你这样做了,你必须使用指针,并初始化它们。对吗?前向引用结构没有错。例如,当您使用它们来保护结构成员不受面向公共API的攻击时,这是非常好的。但是如果您这样做了,那么您总是必须使用指针和malloc来创建一个新实例,是的。