Several things blatantly wrong in this code, many of which will generate warnings that you should have addressed already:
In general:
srand() and rand() are defined in stdlib.h, which you fail to include.
time() is defined in time.h, which you fail to include.
- You're not passing an
int address to scanf as the output target.
- You're not checking the result of your
scanf call.
- You're dealing with magnitudes, which should be unsigned types. Even if you fix the above items someone could enter
-5 and your code would happily parse it and proceed into undefined behavior.
- If
stdout is line-buffered your input prompt will not be visible without a flush.
- If you're going to use a hard-limit on your array size (
1001 in your case) that value should be enforced after validly reading the input size for your array.
fillArray has no formal prototype before its first use in main(). This therefore assumes the function takes an arbitrary number of arguments and returns int.
In your generation function:
- You're bail-out logic is done too late and with the wrong condition.
- You should not be calling
srand() in the fill function. It should be called from main() at process startup once.
- Minor: You don't need to pass both the current input slot and the length. You're filling all the slots, so a value-based descending slot or increasing target pointer via pointer-arithmetic will be sufficient.
Most of these are addressed below. Why you're doing this with recursion I simply don't understand, but suspect it is for academia. If so, your instructor could come up with better recursive algorithm lessons. But right now, you need to work on your fundamentals more. The bullet lists above demonstrate you need significant work on those.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int fillArray(int arr[], unsigned int s);
int main()
{
unsigned int s = 0;
int arr[1001];
srand((unsigned)time(NULL));
printf("Enter size of an array to fill random numbers: ");
fflush(stdout);
if (scanf("%u",&s) == 1 && s < sizeof(arr)/sizeof(*arr))
printf("%d\n", fillArray(arr,s));
}
int fillArray(int arr[], unsigned int s)
{
if (s)
{
*arr = rand() % 1001;
return fillArray(arr+1, --s);
}
return 0;
}
srand (time)will make the followingrand()return the same value almost every time (thetimehas a resolution of 1 second). Lastly, doesn'tfillArrayalways return 0?