哪一部分会导致浮点异常?

fra*_*nka 0 c exception floating-point-exceptions

如果人们可以查看这段代码并让我知道可能导致浮点异常的原因,我将不胜感激.

信息:

  • branches是一个int数组大小200
  • line是一个char数组大小为20
  • 循环运行6次,然后发生异常.

我很困惑,因为没有可能导致这种情况的除法,浮点或整数.

    for (count = 0; count < sizeof(branches); count++){

    if (fgets(line,sizeof(line),fp)==NULL)
     break;
    else {

    int branch_taken = line[16] - 48; 

    branches[count] = branch_taken;
     }   
    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 7

sizeof(branches) is a size in bytes - you need to use a constant which represents the number of elements i.e. 200, otherwise you will be exceeding the bounds of your branches array, which will result in Undefined Behaviour.

Your code should probably look something like this:

#define NUM_BRANCHES 200

int branches[NUM_BRANCHES];

for (count = 0; count < NUM_BRANCHES; count++)
{
    ...
Run Code Online (Sandbox Code Playgroud)

  • 是的,但这并不能解释浮点异常. (3认同)