c - Scanf changes wrong array when it is in do-while loop -
i need suggestions code.
this code in program checks if number in range between 1 , 20. problem occurs in these few lines because when enter in while loop, scanf()
changes numbers in 2 arrays, not in one.
one numbertoguess
array , second array in numbers "randomly" generated (i had used srand(time(null))
). function random generator called once, before code.
i guess because when while loop occurs takes last address buffer, not sure how fix it.
while(numbertoguess[i]<1 || numbertoguess[i]>20) { printf("try again:\n"); for(i=0;i<4;i++) { scanf(" %d", &numbertoguess[i]); } }
edit: had found solution , , unrelated posted code. problem occurred on part had declared arrays. size of arrays smaller should be(instead of 4 , 3). when loop variable (i) equal 3 , scanf jumped memory location, location of second array , changed 1. on second array , when loop equal 3 , out of array bounds , printed "random value".
you don't need inner loop. also, rid of space in scanf
pattern, since %d
ignores them anyway.
while(numbertoguess[i]<1 || numbertoguess[i]>20){ printf("try again:\n"); scanf("%d", &numbertoguess[i]); }
Comments
Post a Comment