-2

I want to print 1000 random numbers saved in a array. Numbers have to be between 1 and 10000.

I put srand(time(NULL)) in my main function and the array have to be filled with random numbers in my init function. The ausgabe function is for formatted output.

But rand fills my array with numbers all in row.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARR_SIZE 1000

void init(int * ptr, int size){
    for (int i = 0; i < size; i++){
        *(ptr + i) = (rand() %10000+1);
    }
}

void ausgabe(int * ptr, int size){

    for (int i = 0; i < size; i++){

        printf("%5i\t", * ptr + i);

        if ((i + 1) %10 == 0){
            printf("\n");
        }

    }
    printf("\n\n");
}

int main(){
    int zufall[ARR_SIZE];

    srand(time(NULL));

    init(zufall, ARR_SIZE);
    printf("\n\t\t\t---unsortierte Ausgabe---\n\n");
    ausgabe(zufall, ARR_SIZE);

    return 0;
}
Stoogy
  • 1,307
  • 3
  • 16
  • 34

1 Answers1

4

* ptr + i is (*ptr)+i, not *(ptr+i). You need to be more careful with operator precedence. (And to learn to use your debugger: 30 seconds in your debugger would have clearly revealed that the problem was the printing, not the initialization.)

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • when i try it this way i get this error: " lvalue required as left operand of assignment (*ptr) + i = (rand() %10000+1);" i tried (*ptr)+i and ((*ptr)+i). – Sefa Simsek May 19 '19 at 21:05
  • ok now it works. Thank you. Can you give me the tip how i can control the output? – Sefa Simsek May 19 '19 at 21:10
  • As Sneftel pointed out `* ptr + i` is the same as `(*ptr)+i`, and so is `((*ptr)+i)`. It has to be `*(ptr+i)`. – RobertBaron May 19 '19 at 21:10
  • @SefaSimsek The assignment in `init` was fine as `*(ptr+i)`. The mistake was in `ausgabe`: `* ptr + i` doesn't do what you want. – aschepler May 19 '19 at 21:10
  • Note you can also write `*(ptr + i)` as `ptr[i]`. – aschepler May 19 '19 at 21:11
  • do i have some disadvantages when i use ptr[i] instead of *(ptr + i) or is it 100% the same? – Sefa Simsek May 19 '19 at 21:15
  • @SefaSimsek : The advantage is you cannot get it wrong in the way you did as there are no operator precedent issues because there is only one operator (`[]`). Since it is an array, why would you use pointer arithmetic in any case? It is just an unnecessary obfuscation. – Clifford May 19 '19 at 21:57