Reputation: 1490
I have the following class:
template <typename T>
class matrix
{
private:
int _n;
T* array;
public:
matrix(): _n(0)
{
array = new T[_n * _n];
}
matrix(int n): _n(n)
{
if( n < 0 )
throw "Invalid array size!";
array = new T[_n * _n];
}
~matrix()
{
delete[] array;
}
void Set(const int x, const int y,const T val)
{
if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
throw "Invalid index";
array[x*_n + y] = val;
}
T& Get(const int x, const int y)
{
if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
throw "Invalid index";
return array[x*_n + y];
}
};
and using it this way:
matrix<int> k(5);
k.Set(5,5,6);
cout<<k.Get(5,5);
The problem is I get a heap corruption error when calling Set. What am I doing wrong? (my guess is it's the way I access they array elements)
Upvotes: 2
Views: 711
Reputation: 1167
You are indexing beyond the array into memory which is why you are getting the error.
The issue is with indexing. The indexing of arrays in C++ starts at 0, so for your declaration of k(5), it produces an array of 5 which is indexed 0-4, so an index of 5 is not a valid valid index. You should change your check in set to be x>=_n and y>=_n, as and index of 5 is not valid.
Upvotes: 0
Reputation: 9319
What is worng is that you have to start counting from 0. If you create a array with size n*n you can acces the element up to (n-1)*(n-1). Your example create a arry of size 5*5=25 and trys to acces element 25. However 24 is the highes element you array contains.
Upvotes: 0
Reputation: 258618
Arrays in C++ are 0-base, that means if you have an array int x[5]
, x[5]
is invalid.
Your conditions should be if( ( x<0 || x>=_n ) && ( y<0 || y>=_n) )
and if( ( x<0 || x>=_n ) && ( y<0 || y>=_n) )
To set the last element, you'd need
k.Set(4,4,6);
and to print it:
cout<<k.Get(4,4);
Upvotes: 0
Reputation: 44181
A 5 element array can be accessed at the indexes 0-4. You're passing 5 for x
and y
, which results in an invalid index when accessing array
.
Upvotes: 1