2016-12-28 47 views
1

下面是对问题的描述https://a2oj.com/p?ID=193,它在Visual Studio上运行得非常好,但由于某种原因,它产生运行时 - 网站的在线判断编译器出错,很难检测到因为他们的编译器不会告诉测试用例产生了什么错误。运行时错误 - C编程,在IDE上没有错误

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define ASCII_SIZE 255 
void main(){ 
    int testCases; 
    char caseInput[100]; 
    int count[ASCII_SIZE] = {0}; 
    int strLength; 
    int max = -1; 
    char result = NULL; 
    typedef struct occurrence{ 
     int numOfOcc; 
     char occLetter; }Occurence; 
    scanf("%d",&testCases); 
    Occurence *ptr; 
    ptr = (Occurence*)malloc(testCases * sizeof(Occurence)); 
    if (ptr){ 
    for (int caseValue = 0; caseValue < testCases; caseValue++) 
     { 
     scanf("%s",caseInput); 
     strLength = strlen(caseInput); 
     for (int i=0; i<strLength; i++) 
      count[caseInput[i]]++; 
     for (int i = 0; i < strLength; i++) { 
      if (max <= count[caseInput[i]]) { 
       if (result > caseInput[i] && i > 0){ 
       max = count[caseInput[i]]; 
       result = caseInput[i]; 
        } 
       else if (i == 0){ 
         max = count[caseInput[i]]; 
         result = caseInput[i]; 
        } 

       } 
      } 
     ptr[caseValue].numOfOcc = max; 
     ptr[caseValue].occLetter = result; 
     max = -1; 
     char result = NULL; 
     memset(count,0,sizeof(count)); 
     } 
    for (int i = 0; i < testCases; i++) 
     { 
     printf("%d %c\n",ptr[i].numOfOcc,ptr[i].occLetter); 
     } 
     } 
    } 
+0

我已经在他们的编译器/测试平台上看到过这个:你的'void main()'是一个相关的错误声明,必须是'int main'。因此,您的'main'返回一个未定义的值,他们的测试床将其解释为错误,因此会报告运行时错误。它返回0. –

+0

是的,谢谢我这样做,但现在它说错误的答案,因为某些原因,虽然它在IDE上运行得非常好,并且它的编译器没有说出哪个测试用例使代码失败是不好的 – andrewnagyeb

回答

0

不能输入字符串存储在你的缓冲高达100个字母:你忘了包括

char caseInput[100]; 

终止'\0'

不运行时错误,但可能仍然无意有关:

max = -1; 
char result = NULL; 
memset(count,0,sizeof(count)); 

在这里你定义了一个sec ond result隐藏前面的定义。

也可能不相关的问题:

void main() 

是不正确的。让它

int main(void) 

int main (int argv, char *argc[]) 

,并成功返回0。

+0

我didn'你真的明白你的意思了“你忘了包括终止的'\ 0'” – andrewnagyeb

+0

你可能想要再读一遍C中的字符串的基础知识。像“Hello”这样的字符串需要6个字节的内存,因为所有字符串都是零终止的,即它们末尾有一个尾部的'\ 0'字节。如果测试用例输入的字符串正好有100个字母,则需要101个字节,其中'scanf'可以存储结果。您只能提供100个字节。 – Gerhardh

+0

是的,我只需要知道我到底需要改变什么 – andrewnagyeb