Home > Blockchain >  What's wrong with the C code below?(A trivial one)
What's wrong with the C code below?(A trivial one)

Time:11-11

When you run the C code below, you get a different results almost everytime(None of them are altogether correct).

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i,j;
    int s[10][4]={{202201,90,13,21},{202202,32,24,12},{202203,23,53,76},{202204,21,43,64},{202205,12,45,89},{202206,98,99,100},{202207,12,0,0},{202208,0,0,0},{202209,98,12,34},{202210,23,65,34}};
    int ave[10],sum[10];
    printf("No.     MA  EN  CN\n");
    for(i=0;i<10;i  )
    {
        for(j=0;j<4;j  )
            printf("M",s[i][j]);
        printf("\n");
    }
    for(i=0;i<10;i  )
    {
        for(j=1;j<4;j  )
            sum[i]=s[i][j] sum[i];
    printf("%d\n",sum[i]);
    }

return 0;
}

What's happening? What's the mechanics behind it? How can I fix it?

CodePudding user response:

Both sum and ave are uninitialized arrays. That means that when you cumulative add to s[i] your first add to an uninitialized value which invokes Undefined Behaviour. Here you were just getting a random but valid value.

You need to ensure that s[i][j] is initialized to 0 before it is first used:

int ave[10],sum[10] = {0}; // initialize the full sum array to 0

or:

for(i=0;i<10;i  )
{
    sum[i] = 0;      // ensure an initial value of 0
    for(j=1;j<4;j  )
        sum[i]=s[i][j] sum[i];
    printf("%d\n",sum[i]);
}

CodePudding user response:

The issue most likely is in this statement.

sum[i]=s[i][j] sum[i];

The "sum" integer array hasn't been initialized prior to this statement, so the value "sum[i]" on the right-hand side of the statement probably holds undefined data. Either initialize your sum array or revise the statement if some other type of evaluation should occur.

  •  Tags:  
  • csum
  • Related