Jan Wolfram
Jan Wolfram

Reputation: 184

Array with random numbers only contains the same values?

I wrote a program which should create many random numbers and save it in an array. I also checked up many questions and everyone just saying to set seed one time but that does not solve my problem.

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

void printArray(int *arr){
    for(int i = 0; arr[i] != '\0'; i++){
        printf("%i, ", *arr);
    }
}

int main(int argc, char* argv[])
{
    // set seed
    srand(time(NULL));
    int number_max; 

    // first argument
    int arg1 = atoi(argv[1]);

    if(arg1 <= 4){
        printf("number to small or not a number\n");
        return 0;
    }
    // 2^n space for random numbers
    number_max = pow(2, arg1);

    // initialize array
    int numbers[number_max];

    // create 2^n random numbers from 0 to 10000
    for(int i = 0; i < number_max; i++){
        numbers[i] = (rand() % (10000 - 0 + 1)) + 0; 
    }

    // print Array
    printArray(numbers);
}

That is my code. My whole array contains the same value. I understand the problem, but don't know how to solve.

Thanks for your help :)

Upvotes: 0

Views: 87

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21542

Few things:

  1. Your loop condition for (int i = 0; arr[i] != '\0'; i++) requires that the array is terminated with zero. This is not the case unless you explicitly terminate the array with zero. Also, if any of the values in numbers is zero, it will stop there.

  2. You are always dereferencing the first element in the array. Print arr[i] or *(arr + i) to print the actual array values one by one.

  3. Not code related, but it's grammatically correct to say "number too small", not "number to small". :-)

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

You see same values because you are printing same element *arr, which is equivalent to arr[0].

Maybe you want this:

void printArray(int *arr){
    for(; *arr != '\0'; arr++){
        printf("%i, ", *arr);
    }
}

or this:

void printArray(int *arr){
    for(int i = 0; arr[i] != '\0'; i++){
        printf("%i, ", *(arr + i));
    }
}

or this:

void printArray(int *arr){
    for(int i = 0; arr[i] != '\0'; i++){
        printf("%i, ", arr[i]);
    }
}

Note that you can write simply 0 instead of '\0'.

Upvotes: 1

Related Questions