0

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;
    }

}
4
  • 1
    You have the size of the array, that would be simpler than passing a start/end pointer. Commented Apr 5, 2022 at 16:03
  • 4
    i <*pa2 certainly seems wrong. Commented Apr 5, 2022 at 16:05
  • Yes and I know how to do it this way but my teacher gave task to do it with the pointers. Commented Apr 5, 2022 at 16:05
  • Don't cast the returned value from malloc(), you can hide several compiler errors that will make your bug more difficult to find than if you simply don't cast it. Never cast the result of malloc. Commented Apr 6, 2022 at 12:54

1 Answer 1

3

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 and &A[0] point to the same memory.

generate(A, &A[size-1]);
Sign up to request clarification or add additional context in comments.

Comments

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.