I want to return an array created in a local function through pointers to the main function. My code is below. The array is returned and I am able to access each element by element once only. The next time it is giving garbage values. What is Wrong?
void DoWork(int** ppOut , int& nSize)
{
int m[5];
for(int i = 0 ; i < 5 ; i++)
{
m[i] = i;
}
nSize = 5;
cout << m[0] << endl;
cout << m[1] << endl;
cout << m[2] << endl;
cout << m[3] << endl;
cout << m[4] << endl;
*ppOut = &m[0];
//delete [] m;
}
void main()
{
int nSize = -1;
int i;
int* f = NULL;
DoWork(&f , nSize);
cout << f[3] << endl;
cout << f[0] << endl;
cout << f[2] << endl;
cout << f[3] << endl;
cout << f[4] << endl;
_getch();
}
Output is:-- 0 1 2 3 4 from local function.
But in main 3 and rest are grabage values
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…