[英]C program crash after exit
我是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(),但是它也不起作用。
如果“崩潰”是指它無法編譯源,並出現以下錯誤:
/tmp/ccvGANfB.o: In function `main':
tmp.c:(.text+0x4d2): undefined reference to `getch'
collect2: error: ld returned 1 exit status
這是因為您正在嘗試使用一個不存在的函數(提取)(公平地說,它存在於curses庫中,但是我非常懷疑那是您的意思)。 您可能會錯用getchar()。
簡而言之,在最后一行替代
getch();
與
getchar();
PS:“崩潰”通常是指運行時錯誤(程序在執行時失敗;您的程序無法編譯,會引發編譯時錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.