Hello again,

I am trying to generate an array which has random integers. Then I have to sort it and perform binary search. Below is my code so far. It gives error message (runtime check failure 2 stack around the variable num_arry was corrupted). When I define num_arry[10] instead of 9 it works. However, my array should have 10 elements but it works when defined it with 11 elements. Do you have any idea about it? Should I use reference or pointer for this task?
Thanks

#include <iostream>
#include <ctime>
using namespace std;
void generate_array(int f_array[]);
void print_array(int p_array[]);

int main()
{		
	int num_arry[9];
	generate_array(num_arry);	
	print_array(num_arry);	
}

void generate_array(int f_array[])
{
	srand((unsigned)time(0));
	for (int index = 0; index<10; index++)
	{
		f_array[index]=(rand()%1000)+1;
	}
}
void print_array(int p_array[])
{
	for(int i = 0; i<10; i++)
	{
		cout << "numbers  " << p_array[i] << endl;
	}
}

using
[int num_arry[9];]
creates an array from num_arry[0] to num_arry[8]..
u still ve only 9 elements..
using [int num_arry[10];]
creates an array from num_arry[0] to num_arry[9],which are the 10 elements that u actually need.. :)

Member Avatar for jencas

You declared an array with 9 elements, but generate_array() and print_array() operate on 10-element-arrays

You have three options:
1. pass the size of the array as an additional parameter to generate_array() and print_array()
2. pass a fix length array to your functions (hint: typedef int[9] INT_ARRAY)
3. use std::vector instead of the array, a vector always knows its size.

the parameter inside the square brackets when initializing an array represents the LENGTH of an array, not the highest index.

the parameter inside the square brackets when initializing an array represents the LENGTH of an array, not the highest index.

Well, you can get the upper boundary of the array by subtracting one from LENGTH.

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.