Home > Software design >  Why am I geting floating point exception?
Why am I geting floating point exception?

Time:09-25

This program worked fine when i manually iterated over 5 individual variables but when I substituted them for those arrays and for loop, I started getting floating point exceptions. I have tried debugging but i can't find were the error comes out from.

#include <stdio.h>

int main(void) {

  long int secIns;
  int multiplicadors[4] = {60, 60, 24, 7};
  int variables[5];

  int i;

  printf("insereix un aquantitat entera de segons: \n");
  scanf("%ld", &secIns);

  variables[0] = secIns;

  for (i = 1; i < sizeof variables; i  ) {
    variables[i] = variables[i - 1]/multiplicadors[i - 1];
    variables[i - 1] -= variables[i]*multiplicadors[i - 1];
  }

  printf("\n%ld segons són %d setmanes %d dies %d hores %d minuts %d segons\n", secIns, variables[4], variables[3], variables[2], variables[1], variables[0]);

  return 0;
}

CodePudding user response:

The problem is you're iterating past the ends of your arrays. The reason is that your sizeof expression isn't what you want. sizeof returns the size in bytes, not the number of elements.

To fix it, change the loop to:

  for (i = 1; i < sizeof(variables)/sizeof(*variables); i  ) {

On an unrelated note, you might consider changing secIns from long int to int, since it's being assigned to an element of an int array, so the added precision isn't really helping.

CodePudding user response:

Consider this line of code:

for (i = 1; i < sizeof variables; i  ) {

sizeof isn't doing what you think it's doing. You've declared an array of 5 ints. In this case, ints are 32-bit, which means they each use 4 bytes of memory. If you print the output of sizeof variables you'll get 20 because 4 * 5 = 20.

You'd need to divide the sizeof variables by the size of its first element.

CodePudding user response:

As mentioned before, sizeOf returns the size of bytes the array holds. Unlike java's .length that returns the actual length of the array. Takes a little bit more of knowledge with bytes when it comes to C.

https://www.geeksforgeeks.org/data-types-in-c/

This link tells you a bit more about data types and the memory(bytes) they take up.

You could also do sizeOf yourArrayName/sizeOf (int). sizeOf(datatype) returns the size of bytes the data type takes up.

CodePudding user response:

sizeof will give the size (in bytes) of the variables and will yield different results depending on the data type. Try:

for (i = 1; i < 5; i  ) {
 ...
}
  • Related