Home > Software design >  How to access values from a pointer-to-array in C
How to access values from a pointer-to-array in C

Time:09-29

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related