0

So I have two arrays which hold players x, y and z co-ordinates, however each time I call them they change their values the first time they are printed to the console they display the correct result however subsequent prints to the screen yield very small numbers,

HisPosition = GetPlayerPosition(aPlayer);
std::cout << "TheirPos=" << std::dec << HisPosition[0] << std::endl;
std::cout << "TheirPos1=" << std::dec << HisPosition[0] << std::endl;

if(!isnan(HisPosition[0])){
    std::cout << "TheirPos2=" << std::dec << HisPosition[0] << std::endl;

Example console output:

TheirPos=440
TheirPos1=1.7118e-037
TheirPos2=1.7118e-037

They are defined like so:

float* HisPosition;

And GetPlayerPosition:

float* GetPlayerPosition(DWORD dwBase)
{
    float result [3];
    DWORD aXPos = dwBase + 0x134;
    DWORD aYPos = dwBase + 0x138;
    DWORD aZPos = dwBase + 0x13C;

    result[0] = Read<float>(aXPos);
    result[1] = Read<float>(aYPos);
    result[2] = Read<float>(aZPos);

    return result;
}

aPlayer stands for the address in memory of the player I am trying to fetch the offsets are correct as on the first console print the position is correct.

I'm new to using arrays in C++ and would appreciate any guidance.

halfer
  • 19,824
  • 17
  • 99
  • 186
Joss Bird
  • 295
  • 1
  • 4
  • 19
  • `return result;` returns a pointer to an array which is then immediately destroyed on the return. You have undefined behaviour. – Richard Critten Jun 23 '17 at 11:22

1 Answers1

1

return result; returns a dangling pointer to local, stack-allocated array that gets vanished when goes out of scope.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Cheers how can I make sure it remains so it doesn't vanish? Edit: My bad just looked at the duplicate. Not going to lie I had no Idea what to search. – Joss Bird Jun 23 '17 at 11:23
  • @JossBird For example: by returning object instead of pointer. You can even name the elements properly instead using [0] ... – KIIV Jun 23 '17 at 11:27
  • You can return ::std::array class with 3 floats instead of raw pointer or maybe define a `Position` class to hold coordinated and return it. – user7860670 Jun 23 '17 at 11:27
  • @KIIV and VTT you're both genius's I created a new struct and now everything works perfectly! Thank you so much! – Joss Bird Jun 23 '17 at 11:36