Vishal_ranjan
Vishal_ranjan

Reputation: 15

Getting runtime error in C in spoj toandfro classical

Here is the link to the problem. http://www.spoj.com/problems/TOANDFRO/ And here is the link to my code http://ideone.com/w5wafl On codepad,it says floating point exception. Here is link to codepad http://codepad.org/FW9bKp5k (remove the space bw code--pad) why is it giving runtime error. is it because of error in strings or array. I am putting the code here.

#include <stdio.h>
#include <string.h>

int main(void) 
{
    int width_of_array, length_of_array, i,j , k;
    k = 0;
    char input_array[300], answer[300][300];

    scanf("%d", &width_of_array);
    scanf("%s", input_array);

    length_of_array = strlen(input_array) / width_of_array;
    for (i = 0 ; i < length_of_array ; i++)
     {
        if (i % 2 == 0)
         {  
            for ( j = 0 ; j < width_of_array ; j++)
              {
                answer[i][j] = input_array[k++];
              }
         }
        else
         {
            for (j = width_of_array - 1 ; j >= 0 ; j--)
              {
                answer[i][j] = input_array[k++];
              }
         }
    }
    for (j = 0 ; j < width_of_array ; j++)
     {
        for (i = 0 ; i < length_of_array ; i++)
         {
            printf("%c", answer[i][j]);
         }
     }
    return 0;
}

Upvotes: 0

Views: 75

Answers (1)

Dylan Kirkby
Dylan Kirkby

Reputation: 1427

The line length_of_array = strlen(input_array) / width_of_array; will be a division by zero if the user inputs zero as the width of the array. CodePad flags this as a floating point error, but at runtime it results in undefined behavior.

Upvotes: 1

Related Questions