Passing pointer to a function in C++ -
i wrote following piece of code
#include <iostream> using namespace std; void temp (int * x) { x=new int [2]; x[0]=1; x[1]=2; } int main() { int *ptr; temp(ptr); cout<<ptr[0]<<endl; cout<<ptr[1]<<endl; return 0; }
running gives seg fault, memory allocation happens inside temp
function local function? memory gets deallocated while returning temp
? know, solve problem, need pass pointer pointer ptr
, still, why thing not work?
to alter in function in c, need pass pointer it. in case, want alter pointer, need pointer pointer:
void temp (int** x)
then in function use *x
have x
(you need (*x)[n]
, *x[n]
means else)
then call temp
with:
temp(&ptr);
this should solve in c, , work in c++.
in c++, pass reference pointer:
void temp(int*&x)
which allow syntax have used unchanged.
Comments
Post a Comment