Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ question including pointer, array and function

So I have two programs here,

the first one is using dynamic allocation and the second one is using fixed sized array.

Now the question is, by using dynamic allocation, the program runs fine AND outputs are correctly printed as expected.

However, when using fixed sized array (the second program), the program runs without errors BUT the outputs are not what I wanted.

The programs are almost same except how the arrays are created..but still both the arrays are same so shouldn't outputs be the same? What are the reasons?? Please help me understand..

First Program Example:
input1      output1
    1            1
    2            2
    3            3
    4            4
    5            5

Second Program Example:
input1      output1
    1            1
    2            5
    3   2058618480
    4        32766
    5            5
// Using Dynamic Allocation
#include <iostream>

int *readNumbers(int n) { 
    int *a ;
    a = new int[n];

    for (int i=0; i<n; i++) {
        std::cout << "enter for a["<<i<<"]: ";
        std::cin >> a[i];
    }

    int *ptr;
    ptr= &a[0];

return ptr;
}


void printNumbers(int *numbers,int length){

    for (int i=0; i<length; i++) {    
    std::cout  << *(numbers+i) << "\n";
    }
} 


int main(){
    int n;
    std::cout << "enter for n: " ;
    std::cin >> n;  

    int *ptr; 
    ptr = readNumbers(n);
    printNumbers(ptr,n);

    delete [] ptr;    
    ptr = NULL;
return 0;
}

And another one is

// Using fixed size array
#include <iostream>

int *readNumbers(int n) { 
    int a[5]={};    

    for (int i=0; i<5; i++) {
        std::cout << "enter for a["<<i<<"]: ";
        std::cin >> a[i];
    }

    int *ptr;
    ptr = &a[0];
return ptr;
}


void printNumbers(int *numbers,int length){

    for (int i=0; i<length; i++) {    
    std::cout << *(numbers+i) << "\n";
    }
} 


int main(){
    int *ptr; 
    ptr = readNumbers(5);
    printNumbers(ptr,5);
return 0;
}
like image 625
AyeYo Avatar asked Dec 23 '25 02:12

AyeYo


2 Answers

In your second piece of code your array is allocated on the stack inside the readNumbers function. Then you return a pointer to that stack memory to the calling function. This memory is no longer valid when printNumbers is run. It has likely been overwritten by locals in printNumbers.

Allocate the array in main and then the second example should also work.

like image 130
Pete Fordham Avatar answered Dec 24 '25 16:12

Pete Fordham


I feel in first case, when you call new operator to allocate memory for storing multiple int values, heap memory is allocated. Now this memory is available when you pass it around functions and this memory is valid till programming is running until someone calls delete operator. So you could pass this pointer from readNumbers, main and printNumber and it is valid.

For second case you created array of int as local variable in function, so it is created in stack. Scope of the local variable is only till the function is running. In your example readNumbers created array and once the function is over the stack is cleared. That is all the local variables created in function are no longer valid. Hence when you use this memory location in other functions like main and printNumbers it will give undefined behaviour. Sometime the result will be expected sometimes invalid result. So you need to be careful what are you passing or returning from one function to another.

If you still want to get expected result in second case, declare arrray as static.

Hope this helps.

like image 26
Rakesh Avatar answered Dec 24 '25 14:12

Rakesh



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!