cancel
Showing results for 
Search instead for 
Did you mean: 

Php just spoils us

jabb0
Grafter
Posts: 716
Registered: 18-09-2007

Php just spoils us

Doin a little work in C++, and i am more or less a complete noob.

I have written this function :
int GetDirections(int startX, int startY, int finishX, int finishY)

{
static int newDirection[2];

int directionX;
int directionY;

directionX = finishX - startX;
directionY = finishY - startY;

newDirection[0] = directionX;
newDirection[1] = directionY;

return newDirection;
}
but it says
Quote
error C2440: 'return' : cannot convert from 'int [2]' to 'int'


I dont want it to convert it to a single int, i want my array returned out of this function.
The answer is prolly sooooooooo simple im gonna have to hurt myself for being thick.
As i said im kinda new to this, i can program, just not in C++... yet :roll:
3 REPLIES
N/A

Php just spoils us

meh, you are trying to return the array, not a value in the array, you would have to do

return newDirection[1]
return newDirection[2]

i think
prichardson
Grafter
Posts: 1,503
Registered: 05-04-2007

Php just spoils us

Hi,

In order to return an array, you will have to have to deal with it as a pointer.

IE, instead of returning the array directly, you return the pointer of the array, which is an int.
Community Veteran
Posts: 14,469
Registered: 30-07-2007

Php just spoils us

Something like the following should work


int *GetDirections(int startX, int startY, int finishX, int finishY)
{
static int newDirection[2];

int directionX;
int directionY;

directionX = finishX - startX;
directionY = finishY - startY;

newDirection[0] = directionX;
newDirection[1] = directionY;

// return the address of newDirection
return &newDirection;
}

int *var;

var = GetDirections(sX, sY, fX, fY);

var[0] will point to newDirection[0]
var[1] will point to newDirection[1]

Also be careful of the following:

int *var1, *var2;

var1 = GetDirections(sX1, sY1, fX1, fY1);
var2 = GetDirections(sX2, sY2, fX2, fY2);

Because var1 & var2 are pointing to the same static variable within the function, as soon as the 2nd line is called, var1 & var2 will both point to the same values as defined by the 2nd call.

You need to read up on pointers and possibly structures.