我是c编程的初学者。所以我可能不知道很多东西。但有人能告诉我为什么我的代码在最后一行完成后会崩溃吗?它可能是我定义的数组吗?
#include <stdio.h>
#include <stdlib.h>
void main()
{
unsigned int totSession, totStudent;
int x, y, i, j;
int *studID,*con,*k;
char (*name1)[40];
int *frequency;
printf("Enter number of consultation\n"); //input number of consultation
scanf("%d", &totSession);
printf("Enter number of students\n"); //input number of students
scanf("%d", &totStudent);
studID = (int *)malloc(totStudent * sizeof(int));
con = (int *)malloc(totStudent * sizeof(int));
name1 = (char *)malloc(totStudent * sizeof(char));
frequency = (int *)malloc(totStudent * sizeof(int));
k = (int *)malloc(totSession * sizeof(int));
for (x = 0; x < totStudent; ++x) //Entering each students details
{
printf("Enter details of Student[%d]\n", x + 1);
printf("Enter StudentID:");
scanf("%d", &studID[x]);
printf("Enter student's Full name:");
scanf("%s", &name1[x]);
printf("Which consultation to choose for student:");
scanf("%d", &con[x]);
}
printf("%s%15s%40s\n", "Student ID", "Fullname", "Which consultation session to choose");
for (y = 0; y < totStudent; ++y) //print all student details
{
printf("%-17d%-23s%d\n\n", studID[y],name1[y],con[y]);
}
for (i = 0; i <= totStudent; ++i) //set all arrays of frequency to 0
{
frequency[i]=0;
k[i] = 0;
}
for (i = 0; i < totStudent; ++i) //summarise consultation
{
++frequency[con[i]];
k[i + 1] += (i+1); //create constant for session number
}
if (totStudent > 1)
{
int hold, hold1;
for (i = 0; i < totSession; ++i) //sorting
{
for (j = 1; j <= (totSession - 1); ++j)
{
if (frequency[j] < frequency[j + 1])
{
hold = frequency[j];
hold1 = k[j];
frequency[j] = frequency[j + 1];
k[j] = k[j + 1];
frequency[j + 1] = hold;
k[j + 1] = hold1;
}
}
}
}
printf("%s%50s", "Consultation Session Number", "The number of students choose this session\n");
for (i = 1; i <= totSession; ++i)
{
printf("%10d%40d\n",k[i], frequency[i]);
}
printf("The session to offer is: Session %d with %d (out of %d) students chosen.\n", k[1], frequency[1], totStudent);
getch();
}
任何帮助将不胜感激!在代码的末尾已经完成了free(),但它也不起作用..
答案 0 :(得分:0)
如果&#34;崩溃&#34;你的意思是它无法编译源代码时出现以下错误:
/tmp/ccvGANfB.o: In function `main':
tmp.c:(.text+0x4d2): undefined reference to `getch'
collect2: error: ld returned 1 exit status
它是因为你试图使用一个不存在的函数(getch)(公平地说它存在于curses库中,但我非常怀疑你的意思是什么)使用)。你可能错过了getchar()。
简而言之,在最后一行代替
getch();
与
getchar();
PS:&#34;崩溃&#34;一个通常是指运行时错误(程序在执行时失败;程序无法编译,它会抛出编译时错误。