A few issues ...
- 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)
- You are setting the array value to
i + 3
.
- This does not increment/count by 3.
- We want to use
i
and increment by 3
- In
main
, the array has 9 elements, but we're passing 10 as a count.
- The function does not check the array index against the count, so it relies on serendipity that the limit of the value will prevent overflow.
So, change:
for (i = -5; i < 20; i++) {
array[i] = i + 3;
}
Into:
for (int i = 0, j = -5; i < count; i++, j += 3)
array[i] = j;
Here is the corrected code. It is annotated:
#include <stdio.h>
int
printArray(int array[], int count)
{
for (int i = 0; i < count; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
int
aufgabe4(int array[], int count)
{
// NOTE/BUG: this is indexing _before_ the start of the array so this is
// UB (undefined behavior)
// NOTE/BUG: we don't want "i + 3" -- we want to increment by 3
#if 0
for (int i = -5; i < 20; i++) {
array[i] = i + 3;
}
#else
for (int i = 0, j = -5; i < count; ++i, j += 3) {
array[i] = j;
}
#endif
}
int
main(void)
{
printf("4.Aufgabe\n");
// NOTE/BUG: too small for passed count value
#if 0
int data3[9] = { 0 };
#else
int data3[10] = { 0 };
#endif
aufgabe4(data3, 10);
printArray(&data3[0], 10);
return 0;
}
In the code above, I've used cpp
conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k