int main(){ //main function
MySort sorter;
int* sortedValues;
cout << "Random Numbers\n--------------------------\n";
sorter.assignRandom();
sorter.printData();
return 1;
}
Here header file:
class MySort{
private:
int* data;
const int N = 10;
public:
void assignRandom();
void printData();
void printArray(int*);
int* sortAscending();
int* sortDescending();
};
its implementation file :
void MySort::assignRandom(){
int array[N];
for(int a=0;a<N;a++){
array[a] = (rand() %10)+1; //array fill with random numbers 1 to 10 but output is not
}
data=array;
}
void MySort::printData(){
for(int a=0;a<N;a++){
cout<< *(data+a)<<", "; // printing data elements
}
}
OUTPUT:
Random Numbers:
2, 0, 1905488, 0, 7339472, 0, 1, 0, 50, 0,
Like this but my random number in 1 to 10 where is the problem ?
In this member function
void MySort::assignRandom(){
int array[N];
for(int a=0;a<N;a++){
array[a] = (rand() %10)+1; //array fill with random numbers 1 to 10 but output is not
}
data=array;
}
You are assigning the address of the first element of the local array array to the data member data.
After exiting the function the local array will not be alive. Its memory can be overwritten. So the pointer data is an invalid pointer. As a result the program has undefined behavior.
Either make the array data member of the class or allocate memory dynamically and its address assign to the data member data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With