Home > database >  Why isn't this C loop counting from -5 to 19?
Why isn't this C loop counting from -5 to 19?

Time:12-19

I don't know why my program can't count from -5 to 19. Does anyone have a tip for me? Thanks a lot!

int printArray(int array[], int count){
    for ( i = 0; i < count; i  )
    {
        printf("%d ", array[i]);
    }
    printf("\n");
}
int aufgabe4(int array[], int count){
    
    for ( i = -5; i < 20; i  )
    {
        array[i] = i   3;
    }
    

}
int main (void){
printf("4.Aufgabe\n");
    int data3[9] = {0};
    aufgabe4(data3, 10);
    printArray(&data3[0], 10);
}

The expected output should be -5 -2 1 4 7 10 13 16 19 be But the shell gives me 3 4 5 6 7 8 9 10 11 12. I really don't know what is wrong because I calculate i 3.

CodePudding user response:

Answer 1:
If it does not, it is because you have undefined behaviour.
The undefined behaviour is caused by accessing outside of an array.
Which happens here array[i] = i 3; for the cases of i being any of -5,-4,-3,-2,-1.

Answer 2:
This answer is not really the answer, because in the presence of undefined behaviour, all explanation attempts are moot.
It is however possible that among all those evil things which the compiler and runtime environment are allowed to do in case of undefined behaviour (basically EVERYTHING...) is the following:

  • this loop for ( i = -5; i < 20; i ) does indeed count from -5 to 19
  • this line array[i] = i 3; inside that loop accesses first before the array (causing undefined behaviour) and later inside and writes values to illegal memory places (i.e. those you should not write to) and then into the array writes some values which are three higher than then counter i
  • later you print those values from index 0 to index 9, and get an output of them, each three higher than the corresponding index, i.e. what you observe

3,4,5,6,7,8,9,10,11,12

CodePudding user response:

A few issues ...

  1. In your example, writing to array[i] with a starting value for i of -5 is trying to write before the start of the array in main. This is UB (undefined behavior)
  2. You are setting the array value to i 3.
  3. This does not increment/count by 3.
  4. We want to use i and increment by 3

So, change:

for (i = -5; i < 20; i  ) {
    array[i] = i   3;
}

Into:

for (i = -5; i < 20; i  = 3)
    array[i   5] = i;
  • Related