C中奇怪的运行时错误?

问题描述:

由于某些原因,当我运行此程序时,我不断收到奇怪的运行时错误。它编译好,大部分程序工作。C中奇怪的运行时错误?

代码:

#include <stdio.h> 
#include "genlib.h" 
#include "simpio.h" 
#include <string.h> 

main() 
{ 
    printf("This program will show you the scores of the basketball games for 1 season.\n"); 
    printf("What is the name of the basketball league? "); 
    string league = GetLine(); 
    printf("How may games were played by the group? "); 
    int gamesplayed = GetInteger(); 
    string teams[3]; 
    int wonGames[3]; 
    int a, b, c; 
    for (a = 0; a < 4; a++) 
    { 
     printf("What is team %d's name? ", a+1); 
     teams[a] = GetLine(); 
    } 
    for (b = 0; b < 4; b++) 
    { 
     printf("How many times did team %s win? ", teams[b]); 
     wonGames[b] = GetInteger(); 

    } 

    printf("\n\n ----===[%s]===----\n", league); 
    printf("Team Name | Games Played | Games Won | Percentage"); 
    for(c = 0; c < 4; c++) 
    { 
     double percent = 100 * (wonGames[c]/gamesplayed); 
     printf("| %s | %d | %d | %lf |", teams[c], gamesplayed, wonGames[c], percent); 
    } 

} 

的问题似乎是与印刷在过去teams[3] for循环。无论我做什么,它打印后崩溃printf("Team Name | Games Played | Games Won | Percentage");

GetInteger()GetLine()是我用来获取输入,它从simpio.h库中的两个函数。任何帮助,将不胜感激。

编辑:如果数组索引从0开始,那么应该团队[3]有四个元素? (0,1,2,3)

+1

阵列'队'只有三个条目,所以没有'队[3]'。 'wonGames'也是如此。 – 2014-11-05 21:15:46

+0

我建议你#define numEntries(4)然后改变你的数组定义,使用numEntries,并改变你的语句使用numEntries – user3629249 2014-11-06 05:49:41

+0

假设GetLine()和GetInteger()是你的个人功能,我希望GetLine()返回一个指向malloc'd内存分配的指针,其中分配的内存包含行或整数。因此,“字符串联赛”应该是(假设“字符串”是一种有效类型)“string * league” – user3629249 2014-11-06 05:54:13

string teams[3]; 
for (a = 0; a < 4; a++) 
{ 
    printf("What is team %d's name? ", a+1); 
    teams[a] = GetLine(); 
} 

你要出界,因为teams有大小3 a最终将获得3

索引从0开始到数组大小的值 - 1,所以更改4 3,或增加一个。

wonGames做同样的事情。

同样,计数器c的循环也应该修改(如果数组的大小没有增加)。


回答编辑。问:如果数组索引从0开始,那么shouldnt teams [3]对元素有效? (0,1,2,3)

A:NO。该数组的大小为3,因此它可以容纳3个元素,第一个在第0个单元格中,第2个在第1个单元格中,第3个在第2个单元格中。

你的数组“团队”有三个元素。您的打印循环访问四个元素。