Hi im starting to learn c++ and im having a little issue that im not capable of correct yet...
the program ask the user to imput the size of an array then the program create it at that size, fill it with random integers and output the array into the screen.
Here is the code. it compiles well but at run time appears after imput an annoying error box when imputs are greater than > 5;
here is my code

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void PrintArray(int* array, int size);
void RandomArrayFill(int* array, int size);


void RandomArrayFill(int* array, int size)
{
int i=0;
for(i=0;i<size+1;i++)
{

array[i]= rand() % 101;
}
}
void PrintArray(int* array, int size)
{
int i=0;
for(i=0;i<size+1;i++)
{
if(i==size)
{
cout <<array[i] << "}" << endl << endl;
break;
}
cout << array[i] << ", " ;

}
}

void main()
{
int numero=0;
int* bobby=0;
srand( time(0) );

do
{
cout << "Enter the size of an array to create: ";
cin >> numero;
bobby = new int(numero);
RandomArrayFill(bobby, numero);
cout << endl << endl << "Creating array and filling it with random numbers...";
cout << "Array = {";
PrintArray(bobby, numero);
//delete [] bobby;
//bobby=0;
}
while(numero!=0);
cout << "NULL Array" << endl;
}

hope you could help me out thx in advance

> bobby = new int(numero);
This dynamically allocates *one* int with the value of numero. Square brackets are used to allocate arrays.

bobby = new int[numero];

Also in the function RandomArrayFill the code puts 1 more value than there is space for in the array.

That is if numero is 5 and array of 5 ints would be allocated (after the fix above) and passed to RandomArrayFill but this function would then write 6 integers into the array writing outside the bounds of the array.

oh crap yep i miss that one () for []. but about the random function i think that you are wrong because mmm... supose that the user enter 5 then when it enter to the for the loop its from 0 to 5 because 5+1 is = 6 but the < makes only take from 5 not by 6.

No, Banfa is right.
You are correct that the first element is located at index '0', and you know that there are in total 5 elements.

0 - first element
1 - second
2 - third
3 - fourth
4 - fifth (bingo, end of array)
(5 - sixth, non-existing)

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.