Search code examples
c++pointerssubroutine

C++ how to use a pointer which has been created in a subroutine


or Mrs., in C++, I'm thinking about using a subroutine to define all my pointers first declared in my main body. I know it can be done by using functions to return one pointer each time. Hence, I still want to do it in a subroutine. I googled much and haven't found a answer yet. Your help is appreciated. An sample c++ code is as:


#include <iostream> 
using namespace std;
void  testsub(int* k3d)
{
k3d= new int [10];
cout<<"test 0 "<<k3d[0]<<endl;
}
int  main ()
{
int* i3d=0;
testsub(i3d);
cout<<"test 1 "<<i3d[0]<<endl;
}

I hope the i3d in the main body can be used after the dummy pointer k3d has been defined in the subroutine. Thanks a lot in advance.


Solution

  • The pointer needs to be passed in by reference, otherwise you're just changing a local copy of that pointer.

    void testsub(int*& k3d)
    

    Also you need to call delete[] after the coutstatement, to avoid memory leaks:

    delete [] i3d;