我尝试了各种说明,最后出现了两个不同的错误:
引用指向不完整类型的指针(此代码中存在错误)
请求非结构或 union 中的成员“Info1”
我已经在 stackoverflow 上读到过此错误,但我不明白。这是我的第一个问题,所以请回答我如何到达那里以及为什么我以这种方式到达那里。只需查看 main 和 else block 即可。
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT 4.0
typedef struct _info {
double Info1;
double Info2;
double Info3;
double TI;
double Softec;
double Prog;
double Sofpro;
double DB;
double SysInf;
double KomSym;
} Info;
typedef struct _math
{
double Ana1;
double Lina1;
double DS;
double Logik;
} Mathe;
typedef struct _nb {
double Ana2;
double Lina2;
double Sto1;
double Opt1;
} NB;
typedef struct _bsc {
struct Info *info;
struct Mathe *mathe;
struct NB *nb;
double Wahl1;
double Wahl2;
double Praxis;
double Sem;
double BSC;
} Bachelor;
int main() {
Bachelor * dima;
dima = malloc(sizeof(Bachelor));
if(dima == NULL) {
free(dima);
return 1;
} else {
(dima->info)->Info1 = DEFAULT; //error is here
printf("Dima got it!\n");
printf("Info1: %f\n",(dima->info)->Info1);
}
return 0;
}
最佳答案
您对 dima
的初始初始化是正确的:
Bachelor* dima = malloc(sizeof(Bachelor));
但是,您的声明:
dima->Info->Info1 = DEAULT;
错了。 dima
已分配内存,但对于结构中的每个指针,您可能需要为其分配或分配内存。
按照以下方式做一些事情:
dima->info = malloc(sizeof(struct Info));
欢迎询问更多信息。简而言之,C 不会自动为你做任何事情。它期望您的代码非常明确(即:强类型而不是动态类型语言)。现在是阅读 C++ 中“构造函数”主题的好时机,只是为了确保您使用正确的语言来完成任务。我使用 C 来编写低级且注重性能的代码,而使用 C++ 来编写大规模非 CPU 密集型项目 IRL。
祝你好运!
关于c - 如何通过 Bachelor 结构和 Info 结构访问 Info1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269813/