Please point in right direction

Why does the code below only cout the addresses?
---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

int*  pointerTest(){
    int z[10];
    for(int i=0;i < 10 ; i++)
        z[i] =i*10;

   return z;
    }

int main()
{
int y[10];
int* ptr;
ptr = pointerTest();


for (int i=0;i<10;i++)
    cout<<  *(ptr +i ) <<endl;



Last edited on
cout is working properly (ie: it's not printing the address).

Your problem is your 'ptr' is bad.

1
2
3
4
5
6
7
8
9
int*  pointerTest(){
    int z[10];  // z is local!  That means it dies at the end of the function!

  //...

  return z;  // successfully returns a pointer to z
   // however 'z' is destroyed as soon as this function exits!  making
   // the return pointer bad!
  }


You cannot return a pointer to a non-static local variable. There are a number of ways to solve this problem (most preferred solution listed first):

1) pass a pointer to the function, rather than have the function return it.

1
2
3
4
5
6
7
8
9
10
11
12
void pointerTest(int* z)
{
  for(int i = 0; i < 10; ++i)
    z[i] = i*10;
}

int main()
{
  int z[10];
  pointerTest(z);  // fills 'z' as you'd expect
  return 0;
}


2) have your function return a dynamically allocated buffer (ie: made with new[]). Just be sure to delete[] it when done!!!! Important!!!! This way is actually pretty messy and it's very easy to forget to delete something. I don't particularly recommend this approach.
1
2
3
4
5
6
7
8
9
10
11
12
13
int* pointerTest()
{
  int* z = new int[10];
  // ... blah
  return z;
}

int main()
{
  int* ptr = pointerTest();
  // do whatever with ptr
  delete[] ptr;  // delete it when done!
}


3) Make 'z' static so that you can return it. This has other side-effects, such as every call to pointerTest will give you a pointer to the exact same buffer. That is... 'z' essentially becomes global. This is also messy (unless that is desired behavior), and probably should be avoided unless you're sure it's what you want.

1
2
3
4
5
int* pointerTest()
{
  static int z[10];
  return z; // okay now, because 'z' is static
}



Pick your poison. There are a million other ways to solve this problem -- but these are the first 3 to come to mind. Like I say I'd recommend option 1 over the other two.
Disch,
thank you yet again.
Topic archived. No new replies allowed.