Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why output of array to pointer is not related

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 ?

like image 712
Oğuzhan Duymaz Avatar asked Dec 22 '25 03:12

Oğuzhan Duymaz


1 Answers

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.

like image 70
Vlad from Moscow Avatar answered Dec 23 '25 17:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!