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

时间:2015-03-26 01:55:39

标签: c pointers struct

我'我尝试了各种指示,最后有两个不同的错误:

  1. deferencing pointer to incomplete type(error in this code)
  2. request for member 'Info1' in something not a structure or union
  3. 我已经在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;
    }
    

2 个答案:

答案 0 :(得分:2)

dima的初始初始化是正确的:

Bachelor* dima = malloc(sizeof(Bachelor));

但是,你的陈述:

dima->Info->Info1 = DEAULT;

错了。 dima已分配内存,但对于结构中的每个指针,您可能需要为其分配或分配内存。

做一些事情:

dima->info = malloc(sizeof(struct Info));

随时询问更多信息。简而言之,C自动为你做任何事情。它希望您的代码非常明确(即:强类型而不是动态类型语言)。现在是阅读&#34;构造函数&#34;的主题的好时机。在C ++中,只是为了确保您使用正确的语言来完成任务。我将C用于低级别和以性能为重点的代码,但C ++用于大规模非CPU密集型项目IRL。

祝你好运!

答案 1 :(得分:0)

原因是您没有在任何地方定义struct Info,因此struct _bsc的定义是错误的,要修复它,请删除struct或使用{{ 1}}名称,即struct,就像这样

_info_

或者:


typedef struct _bsc {
    Info *info;
/* ^ no struct here */
    Mathe *mathe;
/* ^ no struct here */
    NB *nb;
/* ^ no struct here */
    double Wahl1;
    double Wahl2;
    double Praxis;
    double Sem;
    double BSC;
} Bachelor;

当然,您还应为typedef struct _bsc { struct _info *info; struct _math *mathe; struct _nb *nb; double Wahl1; double Wahl2; double Praxis; double Sem; double BSC; } Bachelor; infomathe字段分配空间。

相关问题