(C++) Write a function that is almost exactly the same as the function above, only it takes an input parameter an integer (pass in a number between 25 and 50). Inside the function create an array on the stack instead of the heap. Fill it with random numbers as above. Return the address of the first value of the array, and then in the main use function 1 to print it out. This should NOT work. In comments explain why. (Note that you should comment this function out before turning your code in.)
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int* randArray(const int size){ // This is local array // Memory allocated to this array is freed at the end of this function // Even though you return the array address, this content is already getting removed from the memory int arr[size]; for(int i = 0;i<size;i++){ arr[i] = rand()%50; } for(int i = 0;i<size;i++){ cout<<arr[i]<<" "; } cout<<endl; return arr; } int main(){ const int size = 5; int* res = randArray(size); for(int i = 0;i<size;i++){ cout<<res[i]<<" "; } cout<<endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.