0

I am using the dereference operator but I don't seem to getting values of x.

#include <iostream>
using namespace std;

class Array {

  public:
  int* get() {
      int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

      int *r;
      r = x;
      return r;
  }
};

int main() {
  Array arr;

  int *temp = arr.get();

  for (int i = 0; i < 10; ++i) {
    cout << temp[i] << " ";
  }
}

This prints out 31 32765 0 0 0 0 -1989689609 32624 -989639072 32765 rather than 31 45 39 32 9 23 75 80 62 9

1
  • 4
    Does this answer your question? What is a dangling pointer? x[] is local to the function get and ceases to exist when it returns. Commented Sep 25, 2021 at 21:34

2 Answers 2

2

When a variable, that is allocated on stack, goes out of scope, it gets destroyed. In your example functionArray::get:

  int* get() {
      int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

      int *r;
      r = x;
      return r;
  }

variable x gets destroyed. If you don't want this to happen, you can mark your variable with a static keyword: static int x[] = ... or allocate it on heap int* x = new int[10]. If you use the latter, make sure you free the memory when it's no longer used or use smart pointers.

Sign up to request clarification or add additional context in comments.

Comments

0

you need to define this as a private member of class

private:
    int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

or make it static when inside the function

static int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; 

in both this cases this x array will persist and you will be able to get values out of it. Otherwise Your Get function will return only first member of the array and rest will be clear when exiting from scope of the function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.