gpt4 book ai didi

C 前向引用结构 - 1) 必须带有指针? 2)必须初始化?

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:14 25 4
gpt4 key购买 nike

我正在尝试在 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{...};),我不需要使用指针,我也不需要需要初始化。

含义:

(1) 我可以使用 struct cpu_speed speed; 代替 struct cpu_speed *sp;。(2) 我不需要给结构变量初始化值。

我的问题又来了——在前向引用结构中——(1)你必须用指针来声明它吗? (2) 是否必须初始化值?

最佳答案

结构仅供编译器用于对齐您的内存。因此,它需要知道结构成员的大小。

struct foo {
struct bar *pointer;
};

在这种情况下,sizeof(pointer)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;
};

关于C 前向引用结构 - 1) 必须带有指针? 2)必须初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38524504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com