0

Been trying to get this to work for hours with many different methods but still can't get it to work...

Main class:

WinHandle wh;
int* myarr;
myarr = wh.getpos;
cout << "left: " << *(myarr) << endl;

WinHandle.cpp class:

int* WinHandle::getpos(){
  int pos[4];
  //code
  pos[0] = 2;
  //code

  return pos;
}

WinHandle.h file:

int* getpos();

That's just my last method, tried various others to no avail. Any help?

Keep getting

non-standard syntax; use '&' to create a pointer to member

and

cannot convert from 'int *(__thiscall WinHandle::* )(void)' to 'int *'
Cœur
  • 37,241
  • 25
  • 195
  • 267
Pengiuns
  • 131
  • 2
  • 9
  • 2
    1. `myarr = wh.getpos();`. 2. You're trying to return a pointer to local variable so it will become dangled (didn't you get any compile warnings?). – songyuanyao Jul 10 '16 at 02:11
  • 1
    Possible duplicate of [C++ return array from function](http://stackoverflow.com/questions/8745260/c-return-array-from-function) – MikeCAT Jul 10 '16 at 02:16
  • Or [How to return local array in C++?](http://stackoverflow.com/q/7769998/3309790) – songyuanyao Jul 10 '16 at 02:18
  • why are you using pointers in this case? If you're using C++, it's best `std::array`, or `std::vector`, or one of other beautiful containers. – Jepessen Jul 10 '16 at 09:55

3 Answers3

2

A plain array cannot be returned directly from a function.

Use std::array, instead.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

Your immediate source of compilation error is wrong syntax. When you are calling the function, you need to call it with parenthesis: wh.getpos(). However, this is a lesser of a problem. A much bigger problem is that you are returning an array which is local to your function. This won't do, this array will be destroyed once you exit the function, and you will end up with a pointer to deleted object. Say 'Hi' to undefined behavior.

To fix the problem, you need to return either std::vector or std::array.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Or make the array being returned a member of `WinHandle`. Then the pointer returned by `wh.getpos()` is valid for as long as `wh` continues to exist. – Peter Jul 10 '16 at 02:18
  • @Peter, might be a valid option depending on the design of the class. – SergeyA Jul 10 '16 at 02:28
  • Sure. That's why I suggested it as an additional option to fix the problem. – Peter Jul 10 '16 at 04:24
0

The best solution is to use std::array (or std::vector) because it's the most flexible. Otherwise, you could create the array outside the method, then use a reference parameter to operate on it inside wh.getpos().

maja
  • 697
  • 5
  • 18