0

I'm trying to create a code such that it will ask user to type in the size of array to fill with random number from 0-1000.

My attempt:

#include <stdio.h>

int main()
{
    int p = 0;
    int s;
    int aRRay[1001];
    printf("\n Enter size of an array to fill random numbers: ");
    scanf("%i",s);
    printf("%i",fillArray(aRRay,p,s));

}
int fillArray(int aRRay[],int p, int s) 
{
    srand((unsigned)time(NULL));
    int ran = rand()%1001;
    aRRay[p] = ran;
    if(p>s)
    {
        return 0;
    }

    else
    {
       return fillArray(aRRay,++p,s);
    }
}

This code crashes. I'm not sure whether I put the last printf statement in main at the wrong spot. Rather than putting it in main, could I put it in the function fillArray and use recursion to print out one by one?

2
  • 1
    scanf("%i", &s) could be a good start Commented Nov 5, 2014 at 16:56
  • Firstly, why recursion? What's the problem with iteration? Secondly, the srand (time) will make the following rand() return the same value almost every time (the time has a resolution of 1 second). Lastly, doesn't fillArray always return 0? Commented Nov 5, 2014 at 17:09

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

and you dont deal with the case where the user enters 2000
@pm100 s < sizeof(arr)/sizeof(*arr) isn't there by accident, and is the enforcement of the bullet item: "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"
+1 for comprehensiveness. Nitpick: --s should be s-1. The result is the same but the first is bad style when you don't need to modify the variable. It would also be consistent with arr+1.
sorry I mean original poster didnt deal with the case and you didnt call that out in your very good list
@pm100 it was/is called out in the list. (see second-to-last item in the "general" section). Though hindsight being what it is, that should be s <= ... ; not strictly less-than. duh.
0

(Disclaimer: the following post tries to address the immediate errors and problems of the code posted, there would be other error-checking related and coding-style issues to be addressed but those are left out of this post for now to concentrate on the main ones)

  1. You should pass the address of your variable:

    scanf("%i", &s);
    

    plus you should check the count of the scan'd items to make sure the read was successful.

  2. By first filling the array and afterwards checking the condition (and not counting the zero index) you're actually writing 4 elements to the array when the user asked for 2, change the code to something like:

     int fillArray(int aRRay[], int p, int s)
     {
         if (p >= s)
         {
            return 0;
         }
         else
         {
            srand((unsigned)time(NULL));
            int ran = rand() % 1001;
            aRRay[p] = ran;
    
            return fillArray(aRRay, ++p, s);
         }
     }
    

Example

2 Comments

Read documentation of scanf(3). Notice that it could fail. You should use & test the result (count of scanned items) of scanf.
I was more on the "error fixing" rather on the complete error handling, but I'll mention that since it's correct. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.