why can't this array get past 3 without crashing?

// 04/05/08
//
#include <iostream>
using namespace std;
#include <stdio.h>
#include <cstdlib>
#include <fstream>


class ArrayClass1
{
private:
int *a, size, i;

public:

void ArrayClass1::prompt(void)
{
cout << "How big do you want the array? " << endl;

cin >> size;

if (size < 1 )
cout << "Error: size of array too small" << endl;

a = new int (size);

for ( i=0; i<size; i++)
a[i] = (rand()%10000);
}//promt
// asks for size of desired array
// and allocates it, then fills it
// with random numbers

void ArrayClass1::print()
{

for ( i=0; i<size; i++)
printf ("array [%3d]:%5d\n", i , a[i]);
//printf ("[%s]" ,f);}//for
// prints out the array
// Uses sprintf() formatting to keep all
// the numbers nicely aligned vertically.
}//print
void ArrayClass1::createFile( char * filename)
{

ofstream stream;

stream.open("C:\\Documents and Settings\\1868272\\My Documents\\fp.txt");

if(stream.fail())

{
cout << "Input file opening failed.\n" << endl;
}

for (int i = 0; i <size; i++)
{
stream << a[i] <<endl;
}//for loop

stream.close();//close the stream

for (int i = 0; i <size; i++)
{
cout << a[i] << endl;

}//for loop
system ("pause");
}

void ArrayClass1::sortArray(void)
{
int y, z, temp, lid = size;

for (y = 0; y < size-1; y++)
for (z = 0; z < size-1; z++)
{
if (a[z] > a[z+1])
{
temp = a[z];
a[z] = a[z+1];
a[z+1] = temp;
} /* if */
} /* for */
lid--;
}//sortArray

void ArrayClass1::createFile2(char * filename)
{

ofstream stream;

stream.open("C:\\Documents and Settings\\1868272\\My Documents\\fp.srt.txt");

if(stream.fail())

{
cout << "Input file opening failed.\n" << endl;
}

for (int i = 0; i <size; i++)
{
stream << a[i] <<endl;
}//for loop

stream.close();//close the stream

for (int i = 0; i <size; i++)
{
cout << a[i] << endl;

}//for loop
system ("pause");

}//2file created
};//class end

int main (int argc, char *argv[], char **env)
{ if (argc <2)
{cout <<"Not the right amount of arguments on the command line"<<endl;
exit (-1);}//warning

ofstream fileName( "fp", ios::out );

if (!fileName )
{cerr << "File could not be opened" << endl;
exit(-1);}//warning

ArrayClass1 Begin;

Begin.prompt();

Begin.print();

Begin.createFile(argv [1]);

Begin.sortArray();

Begin.createFile2(argv [2]);


return 0;
}//main
Last edited on
If you're not getting a reply it's because nobody can read it....

http://www.cplusplus.com/forum/articles/1624/
Tried 2 get into ur problem but :-( not able to. Sorry.
Please elaborate UR problem.
the problem is here :
 
a = new int (size);

this reserves memory for ONE int and initializes it with size.
what you want to do is this:
 
a = new int [size];

you can read the fourth value (index of 3) because you'd never get only 4 bytes but rather 16 bytes i think (depends on the system)
Last edited on
Thanks goti I'll try it.
Topic archived. No new replies allowed.