我正在用 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 *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 还很陌生。
编辑 座位定义为
typedef struct {
char rowLetter;
int seatNumber;
char seatTaken;
}seat;
另外一个示例 createhall 命令是
CREATEHALL Hall_A Avatar 24 20
最后的数字是大厅的宽度和高度
编辑:CODE
最佳答案
我得到了错误:
在 main
中 while(1)
循环的底部,你做了一个 free(allHalls);
所以现在没有了大厅,你会遇到段错误......
它在您没有向我们展示的代码中:
while (1) {
...
if(!strcmp("CREATEHALL",temp[0]))
{
allHalls[hallNumber] = makeHall(temp); /*<<<<<<<PROBLEM*/
hallNumber++;
printf("%d\n",hallNumber);
}
....
free(temp);
free(allHalls); // <-- there's your bug
}
fclose(f);
free(line);
关于在 C 中创建结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225059/