c - 如何通过 Bachelor 结构和 Info 结构访问 Info1?

标签 c pointers struct

我尝试了各种说明,最后出现了两个不同的错误:

  1. 引用指向不完整类型的指针(此代码中存在错误)
  2. 请求非结构或 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/

相关文章:

JSON omitempty 带 time.Time 字段

c - 通过 malloc-heap(Concatenate string) 分配内存

c - "Comparing constant with boolean expression is always true"警告是什么意思?

c - 在以相同模式结尾的文件中搜索整数 block

c++ - < 比 <= 快吗?

c - 构建的正确返回类型是什么?

c++ - 如何通过参数修改指针

Delphi,通过 BeginThread 传递指针

c - 使用返回指针的函数声明为指针是否会导致两个指针链?

C结构程序崩溃