Pengiuns
Pengiuns

Reputation: 131

Returning array from function

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 *'

Upvotes: 0

Views: 74

Answers (3)

maja
maja

Reputation: 796

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().

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118425

A plain array cannot be returned directly from a function.

Use std::array, instead.

Upvotes: 2

SergeyA
SergeyA

Reputation: 62613

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.

Upvotes: 1

Related Questions