I created an Array with two elements, and tried a comparison of static arrays, but the incrementation of them is not working like was expected,
the expected output is 1 1 but the output gives me every time 0 1
here is the C code :
#include <stdio.h>
#include <stdlib.h>
int main() {
int a[] = {1, 2, 3};
int b[] = {3, 2, 1};
int *res = malloc(2 * sizeof(int));
int sumA = 0, sumB = 0;
for (int k = 0; k < 2; k++) {
if (a[k] > b[k]) {
printf("yes a\n");
sumA += 1;
} else if (a[k] < b[k]) {
printf("yes b\n");
sumB += 1;
}
}
res[0] = sumA;
res[1] = sumB;
printf("%d, %d", res[0], res[1]);
return 0;
}
I tried debugging the code but no solution, I think the for loop is the issue, I just need hints or permanent solution …
Looking for you help guys.
>Solution :
You’re not iterating over all the 3 valid indexes.
for (int k = 0; k < 3; k++)
Note: you can use sizeof a / sizeof *a to calculate the number of elements in the array.