Alex Moumoulidis
Alex Moumoulidis

Reputation: 25

Returning pointers from function gives weird numbers

Iam trying to get the max number of this array that has numbers from -20 to 30 but it returns weird numbers like this --> 2255667 which is impossible if all is going well.

int * ptomx(int a[],int n)
{
  int max=-100;
  int *point;

  for(int i=0;i<=n;i++)
  {
      if(max<a[i])
      {
        max = a[i];
      }
  }
  point = new int;
 *point = max;
  return point;
}

This is what i do in main()

int maxTemp;

maxTemp=*(ptomx(a,n));

cout<<"Max temp is:"<<maxTemp;

Is it because the pointer in the function is destroyed after the function returns and gives a random number in that memory location. If thats the case it needs to be dereferenced but how?

Upvotes: 1

Views: 1259

Answers (2)

taocp
taocp

Reputation: 23624

You are reading values from beyond the end of the array. These values can be anything and are what's causing the incorrect results.

 for(int i=0;i<=n;i++) 
              //^^

Should be changed to

 for(int i=0;i < n;i++) 

Upvotes: 7

Baelix
Baelix

Reputation: 261

Your for loop within ptomx is running out of bounds.

Think about it: If you want every single value, but nothing beyond the last one, do you want to use >=? If you have 10 values, their actual positions in memory (theoretically) are 0-9. You should only be using > to compensate for this.

for(int i=0;i<n;i++) 

This is what it should look like.

Upvotes: 1

Related Questions