Hi everyone,

I am trying to sort array by a function. My code is shown below. I get error message "runtime check failure 2 stack around the variable "arrayim"". Can someone tell me what does it mean and how to solve this problem?

I appreciate for helps

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void sort_array(int uns_array[], int length);
int main()
{
	int arrayim[3] = {77,56,1};
	sort_array(arrayim,3);
	for (int j = 0; j<3; j++)
	{
		cout << "sorted array" << arrayim[j] <<endl;
	}
}
void sort_array(int uns_array[], int length)
{
	int temp;
	for (int t = 1; t<length; t++)
	{
		for (int k =0; k<=length-1; k++)
		{
			if (uns_array[k+1]<uns_array[k])
			{
				temp = uns_array[k];
				uns_array[k]=uns_array[k+1];
				uns_array[k+1] = temp;
			}
		}
	}

}

That one took me a while to find. Your problem is the line:

for (int k =0; k<=length-1; k++)

because you assume within this loop that k+1 is a valid index in the array, this needs to be

for (int k =0; k<length-1; k++)

because length is NOT a valid index.

The runtime error you're getting is because you built the project in debug mode in VS, if I had to guess. It realized that you access memory that you had not allocated, and threw an error for it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.