Reputation: 175
I'm trying to read a list of integers with the following format (there is a space after each number)
8 6
2
5
3
7
3
5
However, when I try to read it, the number 2 is always 0.
EDIT: I thought i didn't need the full code for this, but here's the full code to reproduce.
#include <stdio.h>
int main(){
int n; //=8
scanf("%d", &n);
int m; //=6
scanf("%d", &m);
int input_arr[m];
int fenwick[n];
//Makes input array
for(int i = 0; i < m; i++){
int v;
scanf("%d",&v);
input_arr[i] = v;
}
//Initializes fenwick tree
for(int i = 1; i < n+1; i++){
fenwick[i]=0;
}
printf("%d \n", input_arr[0]); //prints 0
printf("%d %d\n",n,m); //prints 8 and 6
for(int i = 0; i < m; i++){
printf("%d ",input_arr[i]); //prints 0 5 3 7 3 5
}
return 1;
}
Upvotes: 0
Views: 249
Reputation: 1952
Your problem is coming from incorrect for loop. When you do following:
for(int i = 1; i < n+1; i++){
fenwick[i]=0;
}
it is overwriting the first element of array input_arr
. Fix your for loop to:
for(int i = 0; i < n; i++){
fenwick[i]=0;
}
and it should work. You need to read up on how stack allocations work.
Also, try following:
for(int i = 2; i < n+2; i++){
fenwick[i]=0;
}
which should overwrite two elements.
Another thing you can try is change the declaration order of two arrays and it will work even if your for loop for fenwick array is wrong.
Upvotes: 2