1

プログラミングの課題のために、モデルの学生データベースを作成することになっています。データベースを初期化するには、InitDBすべてのメモリなどを割り当てる関数を作成する必要があります。これまでに書いたものは次のとおりですInitDBstructmain()

typedef struct {
    double mathGrade;
    } stuDB;

typedef struct {
    int numStudents;
    stuDB students[MaxStudents];
    } classDB;

main(){
   int avGrade;
   classDB *example;
   InitDB(example);
   //printf("Average class grade is %d\n",AvGrade(example));   <----ignore
   getchar();
}

void InitDB(classDB *example){
 int i=-1,numS;
 printf("How many students?");
 scanf("%d",&(example->numStudents);
 stuDB *pstudents[numS]; //array of pointers to each student rec of type stuDB
 do {
    pstudents[i] = (stuDB *)malloc(sizeof(stuDB));
    if(pstudents[i]==NULL) break;
    i++;
    } while(i<numS);
 pstudents[0]->mathGrade = 42;     //just for testing
 pstudents[1]->mathGrade = 110;
}

プログラムを実行すると、 の 3 行目InitDB(scanf行) でフリーズします。フリーズと言うときはscanf、ポインター変数ではない 2 番目の引数を作成した場合に、コマンド プロンプトが行うのと同じことを意味します。しかし、&(example->numStudents)すでにポインターである必要があります...そうですか?だから私はアイデアがありません。なぜこれを行うのですか?どうすれば修正できますか?

mallocまた、ステートメントを正しく設定したかどうかはよくわかりませんが、後者の問題のために機能するかどうかを実際に確認することはできませんでした. 私はそれで正しい軌道に乗っていますか...または何ですか?

4

2 に答える 2

5

There is no instance of classDB - just a pointer to classDB. Change the code to-:

   classDB example;
   InitDB(&example);
于 2013-08-12T08:13:36.563 に答える
2
#include<stdio.h>

// structure to hold mathgrade 
typedef struct 
{
   double mathGrade;
}stuDB;

// structure to hold students and their grades
typedef struct 
{
    int numStudents;   //no of students
    stuDB students[];  //array of stuDB
}classDB;

int main()
{
    classDB *example;
    InitDB(&example);
    printAvgDB(example);
    return 0;   
}

// Calculate Avg of all students and print it
void printAvgDB(classDB *example)
{
   int i;
   double avg=0.0;
   for(i=0;i<example->numStudents;i++)
      avg+=example->students[i].mathGrade;
   printf("\nAverage: %lf",avg/example->numStudents);
}

// Initiate no of students and get their mathgrade
void InitDB(classDB **ex)
{
   int i,numS;
   printf("How many students?:");
   scanf("%d",&numS);
   // Allocate array size indirectly
   classDB *example=(classDB *)malloc(sizeof(int)+numS*sizeof(stuDB));
   example->numStudents=numS;
   for(i=0;i<example->numStudents;i++)
   {
       printf("\nEnter math grade for student[%d]:",i+1);
       scanf("%lf",&example->students[i].mathGrade);      
   }
*ex=example;
}
于 2013-08-12T08:40:42.897 に答える