Generate random array in C++

The outputs:

Input the number in your array:
7
4 9 4 11 12 13 10

The codes(return the pointer):

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int *create_array(int *a, int n);
void dis_array(int *a, int n);
int main()
{
    srand((unsigned)time(NULL));
    cout << "Input the number in your array:"<< endl;
    int n;
    cin >> n;
    int *a;
    a = create_array(a, n);
    dis_array(a, n);

    return 0;
}
int *create_array(int *a, int n)
{
    a = new int[n];
    for(int i=0; i<n; ++i){
        a[i]= rand()%15;
        //cout << a[i] <<endl;
    }
    return a;
}
void dis_array(int *a, int n)
{
    for(int i=0; i<n; ++i){
        cout << a[i] << " ";
    }
}

The outputs:

Input the length of the array:
9
11 7 27 16 3 14 16 4 19

The codes;(with quotation &) 

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void create_array(int *&a, int n);
void dis_array(int *a, int n);
int main()
{
    srand((unsigned)time(NULL));
    int *a;
    cout << "Input the length of the array:" << endl;
    int n;
    cin >> n;
    create_array(a, n);
    dis_array(a, n);
}
void create_array(int *&a, int n)
{
    a = new int [n];
    for(int i=0; i<n; ++i){
        a[i] = rand()%30;
    }

}
void dis_array(int *a, int n)
{
    for(int i=0; i<n; ++i){
        cout << *(a++) << " ";
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/120432520