0

I am new to C++ and trying to understand application of pointers and passing and returning arrays as argument.

In this code I have an array named ARR1 which is passed to function copy() as an argument this function prints ARR1 and creates ARR2(copy of ARR1) which is returned to main(). inside main() function i am trying to print arr2 but its giving wrong output.
HERE IS THE CODE:

#include "stdafx.h"
#include <iostream>
#include <string> 
using namespace std; 
int * copy(int *x, int y) {
    int arr2[5] = {};
    cout << "Printing ARR1 \n";             
    for (int i = 0; i < y; i++) {
         cout << *(x + i) << "\n";              //printing ARR1
         arr2[i] = x[i];                //assigning ARR1 values to ARR2
    }
    cout << "\n\n";
    return arr2;            //returning ARR2 to main()
}
int main() {
    int arr1[] = {1,2,3,4,5};
    int size = 5;           //size of arr1
    int *ans = copy(arr1 , size);           //obtaining ARR2 from copy()
    cout << "Printing ARR2 from MAIN() function\n";
    for (int i = 0; i < size; i++) {                
        cout << *(ans+i) << "\n";           //trying to print arr2 but its giving incorrect output.
    }
    return 0;
}

OUTPUT

Printing ARR1
1
2
3
4
5


Printing ARR2 from MAIN() function
-858993460
0
-858993460
6026436
6027184
Press any key to continue . . .
Ayush Katoch
  • 49
  • 1
  • 7
  • 1
    you cant return an array from a function. Use either `std::array` (fixed size) or `std::vector` (dynamic size) – 463035818_is_not_an_ai Jul 14 '17 at 11:46
  • 1
    *undefined behavior* - you are returning a pointer to a function-local variable (whose life time ends when the function returns) -> You end up dereferencing a dangling pointer – UnholySheep Jul 14 '17 at 11:47
  • @tobi303 im a totally new to c++ and dont know how to use std:array ??? can you give me the edited/corrected line of my code ? – Ayush Katoch Jul 14 '17 at 11:51
  • btw, there are very different opinions on this, but if you are new to c++ you wont need raw pointers nor c-style arrays for quite some time and imho you could spend your time with more useful stuff (eg. the std algorithms library is worth to study in detail) – 463035818_is_not_an_ai Jul 14 '17 at 11:52
  • its not about a single line that can fix the code. Look at [std::vector](http://en.cppreference.com/w/cpp/container/vector) and you will find plenty of examples on how to use it – 463035818_is_not_an_ai Jul 14 '17 at 11:53

0 Answers0