简体   繁体   中英

Runtime Error - C Programming , No Error on IDE

Here's the description of the problem https://a2oj.com/p?ID=193 , it works very well on Visual Studio but for some reason it produces Runtime - Error on the website's online judge compiler, it's hard for me to detect it since their compiler doesn't tell what was the test case produced the error.

#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);
        }
        }
   }

You cannot store an input string with up to 100 letters in your buffer:

char caseInput[100];

You forgot to include the terminating '\\0'

Not related to runtime error but probably still unintentionally:

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

Here you define a second result hiding the previous definition.

Also probably not related to your problem:

void main()

is not correct. Make it

int main(void) 

or

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

and return 0 on success.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM