Home > Enterprise >  Function to generate random ints in array doesn't work
Function to generate random ints in array doesn't work

Time:04-06

My function does not work and I do not know why, it ends after entering the range. Could you explain why and how to fix it? I need to do this using these pointers to the array.

void generate(int *pa, int *pa2);
void display(int *pa, int *pa2);

int main()
{
    srand(time(0));
    int size;
    printf("Enter size of array\n");
    scanf("%d",&size);

    int *A=(int*) malloc(size*sizeof(int));
    int *ptr=A;
    int *pa=&ptr[0];
    int *pa2=&ptr[size-1];

    generate(pa,pa2);
    display(pa,pa2);

    return 0;
}

void generate(int *pa, int *pa2)
{
    int upper,lower;
    int randi;
    printf("enter range");
    scanf("%d %d",&lower,&upper);
    for (int i = 0; i <*pa2; i  )
    {
        randi=(rand() % (upper - lower   1))   lower;
        *(pa i) = randi;
    }

}

CodePudding user response:

for (int i = 0; i <*pa2; i )

You've mixed up iterating by index with iterating until you hit a pointer. That's comparing the value of the end of the array, which is garbage, to i.

Instead you need to compare the pointers pa 1 to pa2. And it has to be <= because you do want to fill in the last item.

for (int i = 0; (pa i) <= pa2; i  ) {
  *(pa i) = ...
}

But it's easier to get rid of i and increment a pointer directly.

void generate(int *start, int *end) {
  ...

  for(int *current = start; current <= end; current  ) {
    *current = ...;
  }
}

But since you have the size, it's simpler to pass in the size and iterate by index.

void generate(int *array, int size) {
    ...

    for (int i = 0; i <= size; i  ) {
        array[i] = ...
    }
}

And you can simplify calling the function. A is the pointer to the first element.

generate(A, &A[size-1])

CodePudding user response:

I would comment this on the question, but since still don't have enough reputation I will answer it.

Sharing the code for void display(int *pa, int *pa2) would be helpful as well as the output, does it print any error messages or simply finishes with no output?

  • Related