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;
}