dynamic array

how come the random numbers could not pass onto the array?
(when I ran it, the array only contains only 1 random number)

#include<iostream>
#include<array>
#include<ctime>
using namespace std;

void decre(int array[], int);

int main()
{
int s; // size
int r; // range
int srand(time(NULL));
int p; // order
cout << "input the size of the array:"; cin >> s;
cout << "input the range of the array:"; cin >> r;


int* array = new int[s];

for (int i = 0; i < s; ++i)
{
int random;
random = rand() % (r + 1);
array[i] = random;
cout << random << endl;
}

cout << "================================" << endl;

decre(array, s);

for (int i = 0; i < s; ++i)
{
cout << array[i] << endl;
}

delete array;

system("pause");
return 0;
}


void decre(int array[], int x) // selection sort
{
int first, hold;
for (int i = x -1; i > 0; i--)
{
first = 0; // initialize to subcript of first element
for (int j = 1; j <= x; j++) // locate smallest between 1 & 0
{
if(array[j] < array[first])
first = j;
}
hold = array[first]; // swap smallest with element in position i
array[first] = array[i];
array[i] = hold;
}
return;
}
http://www.cplusplus.com/articles/z13hAqkS/


Please use code tags.

That is not the correct way to declare a std::array

Either that or array is a bad variable name. Yet another example why not to have using namespace std;

http://en.cppreference.com/w/cpp/container/array


Consider using a container such as std::vector rather than messing with dynamic memory.
Last edited on
So you were intending to use std::array, you had the include for it. But it doesn't make sense to mix that up with new, std::array does it's own memory allocation.

Cheers
thanks a lot !! TheIdeasMan
here is my final code

#include<iostream>
#include<vector>
#include<ctime>
using namespace std;

void decre(vector<int>& Array, int x);

int main()
{
int s; // size
int r; // range
int srand(time(NULL));
int p; // order
cout << "input the size of the array:"; cin >> s;
cout << "input the range of the array:"; cin >> r;


vector<int> Array;

for (int i = 0; i < s; ++i)
{
int random;
random = rand() % (r + 1);
cout << random << endl;

Array.push_back(random);
}

cout << "================================" << endl;

decre(Array,s);

for (int i = 0; i < s; ++i)
{
cout << Array[i] << endl;
}


system("pause");
return 0;
}


void decre(vector<int>& Array, int x) // selection sort
{
int first, hold;
for (int i = x -1; i > 0; i--)
{
first = 0; // initialize to subcript of first element
for (int j = 1; j <=i; j++) // locate smallest between 1 & 0
{
if(Array[j] < Array[first])
first = j;
}
hold = Array[first]; // swap smallest with element in position i
Array[first] = Array[i];
Array[i] = hold;
}
return;
}

Last edited on
Topic archived. No new replies allowed.