Reputation: 25
my codes are here. when I print arr[4], sometimes the value is 0, but sometimes the value is 2, it's very strange
#include <stdio.h>
#include <string.h>
int countBalls(int, int);
void main() {
int res;
res = countBalls(1, 10);
printf("result:%d\n", res);
}
int countBalls(int lowLimit, int highLimit)
{
int i;
int num=0,max =0,maxNum=0;
int arr[highLimit];
memset(arr, 0, highLimit);
printf("arr[4]:%d\n", arr[4]);
for(i=lowLimit; i<=highLimit; i++) {
printf("arr[4]:%d\n", arr[4]);
return 1;
}
}
Upvotes: 0
Views: 72
Reputation: 225757
You're not zeroing out the entire array.
memset(arr, 0, highLimit);
The third parameter to memset
is the number of bytes to set, not the number of array elements. Assuming an int
is 4 bytes, this means you only zero out the first two elements and half of the third.
You need to multiply by the element size.
memset(arr, 0, highLimit * sizeof *arr);
Upvotes: 3