我正在从事C语言编程工作,这是为电影院创建基本自动化。
为了保存大厅的数据,我定义了这样的结构:
typedef struct {
char *hallName;
char *movieName;
seat** hallSeats;
int studentCount;
int fullFareCount;
int totalSum;
int width;
int height;
}Hall;
所以我得到一个带有命令的文本文件,每当我想出一个特定的命令时,我应该创建一个单独的大厅。出于这个原因,我为此创建了另一个功能。
Hall makeHall(char **temp) //TEMP HOLDING THE LINES FROM FILE
{
int width = strToInt(temp[3]);
int height = strToInt(temp[4]);
char currentRowLetter = 'A';
int currentRow;
int currentSeat;
seat **hall = malloc(sizeof(seat*) * width );
for (currentRow=0 ; currentRow < width ; currentRow++)
{
hall[currentRow] = malloc(sizeof(seat) * height );
for(currentSeat=0; currentSeat < height ; currentSeat++)
{
hall[currentRow][currentSeat].rowLetter = currentRowLetter;
hall[currentRow][currentSeat].seatNumber = currentSeat + 1;
hall[currentRow][currentSeat].seatTaken = ' ';
}
++currentRowLetter;
}
Hall newHall;
newHall.hallName = temp[1];
newHall.movieName = temp[2];
newHall.hallSeats = hall;
newHall.width = width;
newHall.height = height;
return newHall;
}
由于我将有多个大厅,我创建了一个Hall阵列,以便以后访问它们。
Hall *allHalls = malloc(sizeof(Hall) * 10); /*Hall placeholder*/
当我迭代线路时,我会检查命令并创建大厅或卖票。
Hall *allHalls = malloc(sizeof(Hall) * 10); /*Hall placeholder*/
FILE *f;
f = fopen("input.txt", "rt");
char *line = malloc (sizeof(char) * 200); /*LINE HOLDER*/
int currentLineNumber = 0;
char *tmp;
int hallNumber = 0;
while (1) { /*PARSING FILE*/
if (fgets(line,200, f) == NULL) break; /*FILE END CHECKER*/
currentLineNumber++;
tmp = strtok(line," ");
char **temp = malloc(sizeof(char*) * 6);
int currentWordNumber = 0;
while(tmp != NULL) /*PARSING LINES*/
{
temp[currentWordNumber] = malloc(strlen(tmp) + 1);
strcpy(temp[currentWordNumber],tmp);
tmp = strtok (NULL, " ");
currentWordNumber++;
}
if(!strcmp("CREATEHALL",temp[0]))
{
allHalls[hallNumber] = makeHall(temp); /*<<<<<<<PROBLEM*/
hallNumber++;
printf("%d\n",hallNumber);
}
现在这就是我迷失的部分。每当我尝试访问该阵列时,程序都会崩溃。
我认为这是一个内存问题,因此malloc为allHalls分配的内存增加到40(尽管它不应该是一个问题,因为文件只提供3个不同的大厅)并且程序不再崩溃,而是覆盖了之前的阵中的大厅。
我尝试了多种解决方案,但没有一种方法出现任何好处,所以我最接近的就是这个。
之前我确实使用过很多java,所以我仍然坚持使用OOP而且对C来说很新。
EDIT 座位定义为
typedef struct {
char rowLetter;
int seatNumber;
char seatTaken;
}seat;
也是示例createhall命令
CREATEHALL Hall_A Avatar 24 20
虽然最后的数字是大厅的宽度和高度
编辑:CODE
答案 0 :(得分:2)
我收到了错误:
在while(1)
的{{1}}循环的底部,您执行了main
,所以现在没有更多的大厅,您会遇到段错误...
在你没有告诉我们的代码中:
free(allHalls);